前言
提示:垂直居中的方式:
我们设置样式的居中方式
一、行内元素的居中?
父级元素中加text-align,line-height; 在css中,以font- text- line- 开头的都具有继承性,对行内元素和行内块,是很有效。
.box {
width: 200px;
height: 200px;
background-color: burlywood;
/* span的父级添加text-align:center;line-height */
text-align: center;
line-height: 200px;
}
span {
color: black;
font-weight: bold;
}
<div class="box">
<span>居中</span>
</div>
二、块级元素的居中
margin:0 auto; 原理:上下外边距为0,然后左右外边距进行填充从尔居中
.box {
margin: 0 auto;
width: 200px;
height: 200px;
background-color: burlywood;
/* span的父级添加text-align:center;line-height */
text-align: center;
line-height: 200px;
}
span {
color: black;
font-weight: bold;
}
三、定位的居中
这里我们结构没有写大盒子。我们就以绝对定位来演示:是以浏览器为视口的,距离左边距离50%,上边的距离50%,在减去盒子本身高度和宽度的一半,来进行的整个页面的水平垂直居中。
.box {
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
/* margin: 0 auto; */
width: 200px;
height: 200px;
background-color: burlywood;
/* span的父级添加text-align:center;line-height */
text-align: center;
line-height: 200px;
}
四 通过位移来实现的居中
先进行定位,然后我们使用位移来进行居中。
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
代码如下(示例):

五使用 flex使盒子进行水平垂直的居中
<div class="father">
<div class="box">
<span>居中</span>
</div>
</div>
.father{
height: 300px;
background-color:green;
display: flex;
justify-content: center;
align-items: center;
}