1.利用position和transform
//父元素
.fuBox{
height: 600px;
background-color: gray;
position: relative;
}
//子元素,如果这里子元素的宽高固定,也可以不用transform,直接使用固定的left和top
.testCenterBox{
height: 100px;
width: 100px;
background-color: #fff;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
2.position和margin
//父元素
.fuBox{
height: 600px;
background-color: gray;
position: relative;
}
//子元素
.testCenterBox{
height: 100px;
width: 100px;
background-color: #fff;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
3.flex布局
//父元素
.fuBox{
height: 600px;
background-color: gray;
display: flex;
justify-content: center;
align-items: center;
}
//@这里还有一种方式,这两个方式都只适用于div中只有一个直系子元素,多了的话位置会变化
.fuBox{
height: 600px;
background-color: gray;
display: flex;
}
//子元素
.testCenterBox{
height: 100px;
width: 100px;
background-color: #fff;
margin: auto;
}
4.table和table-cell
这里的html要多加一层才行
html:
<div class="fuBox">
<div class="testTd">
<div class="testCenterBox">
</div>
</div>
</div>
//父元素
.fuBox{
height: 600px;
width: 100%;
background-color: gray;
display: table;
}
.testTd{
display: table-cell;
vertical-align: middle;
text-align: center;
}
.testCenterBox{
display: inline-block;
height: 100px;
width: 100px;
background-color: #fff;
}