@Sakura-W
2016-09-11T13:00:40.000000Z
字数 2232
阅读 1404
CSS
CSS居中最大的难题是:居中的方法很多,要考虑不同的场景应用不同的居中方法。
可以给包含行内元素的父元素设置一下属性来使行内元素居中:
.parent{
text-align: center;
}
这种方式适用于inline
或者inline-*
类型的元素,如inline
,inline-block
, inline-table
, inline-flex
等行内元素
对于块状元素,可以设置其margin-left
和margin-right
值为auto
即可(前提是该元素已经设置了width
值)
.center-children{
width: 100px;
margin: 0 auto;
}
如果要将多个块级元素在同一行居中,那么通常的方法就是将这些块级元素的display属性设置为其他,比如inline-block
或者flex
.parent{
text-align: center;
}
.center-children{
display: inline-block;
}
或者
.parent{
display: flex;
justify-content: center;
}
使父元素的line-height大小设置等于height的大小:
.parent{
height: 100px;
line-height: 100px;
}
或者使单行行内元素的padding-top
值等于padding-bottom
值:
.center-children{
padding-top: 30px;
padding-bottom: 30px;
}
一般使padding-top等于padding-bottom值同样可以起作用:
.center-children{
padding-top: 30px;
padding-bottom: 30px;
}
如果上面的方法不起作用,那么该元素可能是table元素,比如:
<table>
<tr>
<td>
I'm vertically centered multiple lines of text in a real table cell.
</td>
</tr>
</table>
table里的元素默认是垂直居中的。
如果不在table里,也可以将父元素的display属性设置为table,来达到同样的效果:
.parent{
display: table;
}
.center-children{
display: table-cell;
vertical-align: middle;
}
当然还可以尝试用flex属性来实现垂直居中(前提是父元素必须有固定的高度):
.parent{
display: flex;
flex-direction: column;
justify-content: center;
height: 400px;
}
还可以用伪元素来实现这一效果:
.parent{
position: relative;
}
.parent::before{
content: " ";
display: inline-block;
height: 100%;
width: 1px;
vertical-align: middle;
}
.childrent{
display: inline-block;
vertical-align: middle;
}
如果知道元素的高度,可以采用绝对定位的形式实现垂直居中:
.parent{
position: relative;
}
.children{
position: absolute;
top: 50%;
height: 100px;
margin-top: -50px;
}
如果不知道该元素的高度,可以用transform
属性来实现垂直居中:
.parent{
position: relative;
}
.children{
position: absolute;
top: 50%;
transform: translateY(-50%);
}
当然也可以采用flex
来实现垂直居中:
.parent{
display: flex;
flex-direction: column;
justify-content: center;
}
采用负margin
来实现:
.parent {
position: relative;
}
.child {
width: 300px;
height: 100px;
padding: 20px;
position: absolute;
top: 50%;
left: 50%;
margin: -70px 0 0 -170px;
}
采用transform
来实现:
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.parent {
display: flex;
justify-content: center;
align-items: center;
}
方法很多,可以视具体情况确定具体的方法。