css-tricks:水平和垂直居中

这些天写页面,写了各种居中,水平,垂直,所以打算总结一下遇到这种需求该怎么才能实现。

水平居中

inline和inline-block的水平居中

我们会遇到例如文本和链接等行内元素的水平居中,可以用一个块级父元素包裹它们,然后给父元素设置:

1
2
3
.parentElement {
text-align:center;
}

这将为:inlineinline-block, inline-table, inline-flex等属性元素生效。

block元素的水平居中

我们能够利用左右边距自适应(margin:0 auto)来水平居中一个块级元素,不过目标元素必须拥有确定宽度,否则宽度会变成百分之百从而不需要居中。除此之外,需要居中的元素也不能是浮动的。如果遇到多个块级元素需要水平居中,建议将它们的display属性改为inline-block,然后再去实现居中。

垂直居中

inline和inline-block的垂直居中

如果是单独一行,我们可以利用内边距padding来让它实现垂直居中,如果内边距不是你的选择,那么我们可以使用行高来实现,只要将行高等于元素高度即可,不过这只适合只有一行的元素。如果是多行文字,或者大小不固定的图片等需要垂直居中,可以参考张鑫旭的博客

1
2
3
4
.center-text {
height:100px;
line-height:100px;
}

block元素的垂直居中

如果知道要被居中元素的高宽,那么可以利用绝对定位,前提父元素是相对定位

1
2
3
4
5
6
7
8
.child {
background-color:#6699FF;
width:200px;
height:200px;
position: absolute; //父元素需要相对定位
top: 50%;
margin-top:-100px ; //二分之一的height
}

如果未知高宽,可以这样:

1
2
3
4
5
.child {
position: absolute;//父元素相对定位
top: 50%;
transform: translateY(-50%);
}

如果兼容条件允许使用flex:

1
2
3
4
5
.parent {
display: flex;
flex-direction: column;
justify-content: center;
}

垂直水平居中

无非是将两个情况相结合

已知元素高宽

1
2
3
4
5
6
7
8
9
10
.child {
background-color:#6699FF;
width:200px;
height:200px;
position: absolute; //父元素需要相对定位
top: 50%;
left:50%;
margin-left:-100px;
margin-top:-100px ; //二分之一的height
}

如果未知高宽,可以这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.child {
position: absolute;//父元素相对定位
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
//或者
.child {
margin:auto;
position: absolute; //父元素需要相对定位
left: 0;
top: 0;
right: 0;
bottom: 0;
}

可以使用flex的话:

1
2
3
4
5
.parent {
display: flex;
flex-direction: column;
justify-content: center;
}