html 代码
<div class="parent">
<div class="child">DEMO</div>
</div>
公共css样式
.parent{
width:200px;height:300px;
background:#ddd;
}
.child{
background:#666;
color:#fff;
}
盒子宽高 + 父相子绝 + margin 只适用于子盒子有宽度和高度的时候
父相子绝,子盒子:top:50%,left:50%;然后设置左外边距为自身宽度一半,上外边距为自身高度一半
.parent {
position: relative;
width: 800px;
height: 400px;
border: 1px solid black;
}
.child {
position: absolute;
width: 400px;
height: 200px;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -200px;
border: 1px solid red;
}
父相子绝+margin: auto; 只适用于子盒子有宽度和高度的时候
设置margin自动适应,然后设置定位的上下左右都为0,就如四边均衡受力从而实现盒子的居中;
.parent {
position:relative;
}
.child {
widht: 100px;
height: 100px;
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
父相子绝+位移 子盒子有或没有宽高的时候都适用
设置子盒子 top:50%,left:50%,再用CSS3属性transform: translate(-50%, -50%);
.parent{
position: relative;
}
.child{
position: absolute;
left: 50%; /* 父盒子宽度的50% */
top: 50%; /* 父盒子高度的50% */
transform: translate(-50%,-50%); /* 子盒子自身宽高的50% */
}
弹性盒子 display:flex 子盒子有或没有宽高的时候都适用
父盒子:display:flex;设置主轴居中,侧轴居中
.parent{
display: flex;
justify-content: center; /* 水平方向 居中*/
align-items: center; /* 垂直方向 居中*/
}
table-cell+inline-block 子盒子有或没有宽度的时候都适用
将父盒子设置为table-cell(能够使元素呈单元格的样式显示),并设置text-align: center(使内容水平居中);vertical-align: middle(使内容垂直居中);。子盒子设置为inline-block可以使其内容变为文本格式,也可设置宽高;
.parent{
display: table-cell; /*使标签元素以表格单元格的形式呈现*/
text-align: center; /* 水平居中*/
vertical-align: middle; /* 垂直居中 */
}
.child{
display: inline-block; /* 将子盒子设置为行内块级(文本格式)*/
}
总结:
以上几种方式推荐使用弹性盒子,因为在使用定位的时候会使元素脱离文档流出现撑不起父盒子的问题,而在弹性盒子中不会出现这样的问题,而且利用弹性盒子还能解决其他的问题。
参考: [如何实现div盒子水平垂直居中](https://blog.csdn.net/weixin_42331327/article/details/80853935)