注意
文章中出现的块级元素包括纯块级和行内块元素,行级元素包括纯行级元素和行内块元素(除非进行了特别说明)
1.1 text-align:center
- 应用场景
容器元素为块级元素,欲居中元素为行级元素。实现水平居中。
<div class="container">
<span class="child">我要居中</span>
</div>
.container{
text-align: center;
}
.child{
}
1.2 margin:0 auto
- 应用场景
容器元素为块级元素,欲居中元素设置了宽度。实现水平居中。
<div class="container">
<div class="child">我要居中</div>
</div>
.container{
}
.child{
margin: 0 auto;
width: 100px;
}
1.3 定位
<div class="container">
<span class="child">我要居中</span>
</div>
.container{
position: relative;
width: 200px;
height: 200px;
background-color: red;
}
(1)当child元素宽度或高度已知,且欲让其水平或垂直居中。则child元素样式为(若想同时水平垂直居中,则样式代码综合即可)
.child{
position: absolute;
/*以下为水平居中样式*/
width: 50px;
left:50%;
/*这里margin-left值为负的自身宽度的一半*/
margin-left: -25px;
/*以下为垂直居中样式*/
height: 60px;
top:50%;
/*这里margin-top值为负的自身高度的一半*/
margin-top: -30px;
}
或者
.child{
position: absolute;
margin: auto;
width: 40px;
height: 40px;
/*以下为水平居中样式*/
left:0;
right: 0;
/*/*以下为垂直居中样式*/
top:0;
bottom: 0;
}
(2)当child元素宽度/高度未知或由元素自身内容决定,且欲让其水平或垂直居中。则child元素样式为:(若想同时水平垂直居中,则样式代码综合即可)
.child{
position: absolute;
/*以下为水平居中样式*/
left:50%;
transform: translateX(-50%);
/*以下为垂直居中样式*/
top:50%;
transform: translateY(-50%);
}
1.4 弹性布局
<div class="container">
<span class="child">我要居中</span>
</div>
.container{
width: 200px;
height: 200px;
background-color: red;
display: flex;
/*以下为水平居中样式*/
justify-content: center;
/*以下为垂直居中样式*/
align-items: center;
}
.child{
}
1.5 line-height
- 应用场景
实现行级元素的垂直居中。
(1)单行行元素垂直居中
<div class="container">
<span class="child">我要居中</span>
</div>
.container{
width: 200px;
height: 200px;
background-color: red;
}
.child{
/*欲居中元素的line-height与容器元素的height一致*/
line-height: 200px;
}
或者
.container{
width: 200px;
/* 只需设置容器元素的line-height即可*/
line-height: 200px;
}
.child{
}
(2)多行行元素垂直居中
.container{
width: 200px;
/*设置行高同时定义容器元素高度 */
line-height: 200px;
background-color: red;
}
.child{
/*核心样式*/
vertical-align: middle;
display: inline-block;
/*设置自己的line-height覆盖父元素的line-height*/
line-height: 20px;
}
解析:
display:inline-block的作用除了重置父元素的line-height外,更为关键的通过其产生在当前元素前面的
幽灵空白节点
,,.container元素的line-height便有了作用对象,从而相当于在.child元素前面撑起了一个高度为200px的宽度为 0 的内联元素。因为内联元素默认都是基线对齐的,所以我们通过对.content 元素设置 vertical-align:middle来调整多行文本的垂直位置,从而实现我们想要的“垂直居中”效果。如果是要借助 line-height实现图片垂直居中效果,也是类似的原理和做法。