垂直居中
CSS
让人头疼的问题就是垂直居中
。实现垂直居中
好几种形式,但每一种形式都有肯定的局限性,所以垂直居中
能够依据理论的业务场景来应用。
在容器里让内容居中最好的形式是依据特定场景思考不同因素。做出判断前,先一一询问本人以下几个问题,直到找到适合的解决办法。
- 容器外面的内容只有一行文字?
- 容器天然高度?
- 容器须要指定高度或者防止应用内边距?
- 应用
Flexbox
布局? - 容器和内容的高度都晓得?
- 不晓得外部元素的高度?
容器外面的内容只有一行文字
设置一个大的行高,让它等于现实的容器高度。这样会让容器高度扩大到可能包容行高。如果内容不是行内元素,能够设置为inline-block
。
<!DOCTYPE html><html lang="en"> <style> * { padding: 0; margin: 0; } div { height: 60px; background-color: #1888fa; color: white; } span { line-height: 60px; } </style> <body> <div> <span>测试居中</span> </div> </body></html>
容器天然高度
CSS
中最简略的垂直居中
办法是给容器相等的高低内边距,让容器和内容自行决定本人的高度。
看上面的例子, 通过设置padding-top
和padding-bottom
相等的值,让内容在父容器垂直剧中。
<!DOCTYPE html><html lang="en"> <style> * { padding: 0; margin: 0; } div { padding-top: 20px; padding-bottom: 20px; background-color: #1888FA; color: white; } </style> <body> <div> <span>测试居中</span> </div> </body></html>
容器须要指定高度或者防止应用内边距
能够给父容器设置display: table
, 子元素设置display: table-cell;vertical-align: middle;
, 让子元素来垂直居中。
<!DOCTYPE html><html lang="en"> <style> * { padding: 0; margin: 0; } div { width: 100%; height: 60px; background-color: #1888fa; color: white; display: table; } span { display: table-cell; vertical-align: middle; } </style> <body> <div> <span>测试居中</span> </div> </body></html>
应用 FlexBox
应用flex
布局在做居中的时候非常容易。
<!DOCTYPE html><html lang="en"> <style> * { padding: 0; margin: 0; } div { height: 60px; display: flex; align-items: center; justify-content: center; background-color: #1888fa; color: white; } </style> <body> <div> <span>测试居中</span> </div> </body></html>
容器和内容的高度都晓得
将内容应用相对定位, 只有其余办法都无奈实现,才举荐这种。
<!DOCTYPE html><html lang="en"> <style> * { padding: 0; margin: 0; } div { height: 100px; background-color: #1888fa; color: white; position: relative; } span{ position: absolute; top: 35px; display: inline-block; height: 30px; } </style> <body> <div> <span>测试居中</span> </div> </body></html>
不晓得外部元素的高度
将内容应用相对定位
+ transform
, 只有其余办法都无奈实现,才举荐这种。
<!DOCTYPE html><html lang="en"> <style> * { padding: 0; margin: 0; } div { height: 100px; background-color: #1888fa; color: white; position: relative; } span { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } </style> <body> <div> <span>测试居中</span> </div> </body></html>
总结
应结合实际的业务场景来具体应用哪种形式。
参考
How to Center in CSS