CSS居中
所有例子共用以下代码
<!--html-->
<div class="outers">
<div class="inners">
</div>
</div>
垂直居中
方法一:
绝对定位,父相子绝
50%的父元素宽高减去自身宽高的50%
/*css*/
.outers {
width: 500px;
height: 300px;
border: 5px solid deeppink;
margin: 100px auto;
position: relative;/*遵循父相子绝原则(父元素相对定位,子元素绝对定位)*/
}
.inners {
width: 200px;
height: 100px;
border: 5px solid burlywood;
position: absolute;/*采用绝对定位脱离文档流,不然left与top无效*/
left: 50%;/*父元素的width的50%*/
top: 50%;/*父元素的height的50%*/
transform: translateX(-50%) translateY(-50%);/*平移元素自身宽高的50%*/
}
方法二:
利用绝对定位的特性,给定left、right、top、bottom相同值,利用margin自适应
.inners {
width: 200px;
height: 100px;
border: 5px solid burlywood;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
方法三:
flex布局
/*css*/
.outers {
width: 500px;
height: 300px;
border: 5px solid deeppink;
margin: 100px auto;
display: flex;
align-items: center;/*垂直居中*/
justify-content: center;/*水平居中*/
}
.inners {
width: 200px;
height: 100px;
border: 5px solid burlywood;
}
水平居中
方法一:利用margin
.outers {
width: 500px;
height: 300px;
border: 5px solid deeppink;
margin: 100px auto;
}
.inners {
width: 200px;
height: 100px;
border: 5px solid burlywood;
margin: 0 auto;
}
方法二:利用text-align,子元素必须为行内元素或行内块元素
.outers {
width: 500px;
height: 300px;
border: 5px solid deeppink;
margin: 100px auto;
text-align: center;
}
.inners {
width: 200px;
height: 100px;
border: 5px solid burlywood;
display: inline-block;
}