我把一个子元素在父元素中水平垂直居中的实现方式分为三类,第一类是宽度已知,第二类是宽度未知,第三类是图片水平垂直居中。
第一类 宽度已知
第一种方式:采用绝对定位
原理
元素开启绝对定位后,水平方向和垂直方向分别要满足下列等式
- 水平方向:left+margin-left+border-left+padding-left+width+padding-right+border-right+margin-right+right=包含块内容区的宽度
- 垂直方向:top+margin-top+border-top+padding-top+height+padding-bottom+border-bottom+margin-bottom+bottom=包含块内容区的高度
如果上述等式不成立,则发生过度约束
以水平方向为例(假设不指定padding和border,即使指定也对布局没有影响)
当发生过渡约束时,如果这9个属性的值当中没有auto,则会自动调整right的值,以使等式成立。如果有auto,则自动调整值为auto的属性以使等式成立。 - 可以设置为auto的值有 left right width 和 margin
由于前提条件是宽度已知, 所以只能是left,right以及margin可以是auto。所以将left,right的值都设置为0,margin设置为auto,则9个值当中能调整的只有margin,使等式成立。 - 水平方向和垂直方向的原理一样
代码
<!--HTML代码-->
<div class="outer">
<div class="box1">
</div>
</div>
/*CSS代码*/
.outer{
position:relative;
width:500px;
height:500px;
background-color:blue;
}
.box1{
position:absolute;
width:100px;
height:100px;
top:0;
right:0;
bottom:0;
left:0;
margin:auto;
}
第二种方式:将父元素设置为一个单元格
原理
水平方向上还是通过margin设置。垂直方向上通过display将父元素设置为table-cell,即表格的单元格。然后用vertical-align:middle;,使子元素垂直居中
代码
<!--html代码-->
<divclass="box1">
<divclass="box2"></div>
</div>
/*CSS代码*/
.box1{
width: 500px;
height:500px;
background-color: blueviolet;
display: table-cell;
vertical-align: middle;
}
.box2{
width:100px;
height:100px;
background-color: aquamarine;
margin:0 auto;
}
第三种方式:flex布局
原理
利用flex布局,设置justify-content:center,让元素在主轴方向上居中排列
设置align-items:center,让元素在辅轴上居中对齐
代码
<!--HTML文件-->
<div class="outer">
<div class="box1">
</div>
</div>
/*CSS文件*/
.outer{
width:800px;
height:800px;
background-color:yellow;
display:flex;
justify-content:center;
align-items:center;
}
.box1{
width:200px;
height:200px;
background-color:green;
}
第二类:宽度未知
第四种方式:利用平移实现垂直居中效果
原理
对于宽高未知的元素,我们将他绝对定位,将其偏移量设置为left:50%,top:50%,此时元素在包含块中心的偏右下方。然后再通过平移将其向上和向左移动自身一半的大小
代码
<!-- HTML代码 -->
<div class="box1">1222345</div>
/*CSS代码*/
.box1{
position:absolute;
left:50%;
top:50%;
transform:translateX(-50%) translateY(-50%);
}
第三类:图片水平垂直居中
第五种方式
原理
通过给伪元素:after设置高度,撑起父元素,然后让图片垂直居中,再用text-align让图片水平居中
代码
<!--HTML代码-->
<body>
<img src="../img/bg.jpg" alt="">
</body>
/*CSS代码*/
html,body{
height:100%;
}
body{
/*使图片水平居中*/
text-align: center;
}
body::after{
content:"";
/*让伪元素撑起高度*/
height:100%;
display:inline-block;
vertical-align: middle;
}
img{
/*使图片垂直居中*/
vertical-align: middle;
}