1、position:absolute绝对定位
.box1 {
width: 300px;
height: 300px;
background-color: orange;
position: relative;
}
.box2 {
width: 100px;
height: 100px;
background-color: blue;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
2、绝对定位第二种方法
.box1{
width: 300px;
height: 300px;
background-color: orange;
position: relative;
}
.box2{
width: 100px;
height: 100px;
background-color: blue;
position: absolute;
left:50%;
top:50%;
margin:-50px 0 0 -50px;
}
3、定位中使用transform
.box1 {
width: 300px;
height: 300px;
background-color: orange;
position: relative;
}
.box2 {
width: 100px;
height: 100px;
background-color: blue;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
4、flex布局居中方式
.box1 {
width: 300px;
height: 300px;
background-color: orange;
display: flex;
justify-content: center;
align-items: center;
}
.box2 {
width: 100px;
height: 100px;
background-color: blue;
}
5、display:grid方法
.box1 {
width: 300px;
height: 300px;
background-color: orange;
display: grid;
}
.box2 {
width: 100px;
height: 100px;
margin: auto;
background-color: red;
}
6、display:table方式
<div class="box1">
<div class="box2">
<div class="inner">
</div>
</div>
</div>
.box1 {
width: 300px;
height: 300px;
background-color: orange;
display: table;
}
.box2 {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.inner{
width: 100px;
height: 100px;
display: inline-block;
background-color: blue;
}