div内容水平垂直居中的5种方法
div内容水平垂直居中是样式里常需要处理的问题。下面介绍几种方法让div内容水平垂直居中。
1,使用 table-cell
将container的display设置为table,将div的display设置为table-cell。
示例代码:
<div id="container" style="display: table;">
<div id="item1" style="display: table-cell; vertical-align:middle; text-align: center;"></div>
<div id="item2" style="display: table-cell; vertical-align:middle; text-align: center;"></div>
</div>
如果只需要垂直居中,去掉 text-align: center 即可。
2,使用 Flex 布局
使用 Flex 布局是让 div 中的内容水平垂直居中的常见方法。
示例代码:
<div style="display: flex; justify-content: center; align-items: center;"></div>
使用后内容会同时水平+垂直居中。
3,使用绝对定位
使用绝对定位能实现 div 中内容的水平垂直居中。
示例代码:
<div id="container" style="position: relative;">
<div id="item1" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);"></div>
</div>
4,使用 Grid 布局
使用 Grid 布局能实现 div 中内容的水平垂直居中。
示例代码:
<div style="display: grid; place-items: center;"></div>
5,使用 line-height
让height和line-heigh一样可以实现垂直居中。
示例代码:
<div style="height: 30px; line-height:30px;"></div>
一般情况下,如果要实现水平居中,只需要在样式里添加 text-align: center; 就可以了。
我的笔记