css实现未知高度水平垂直居中

来源:互联网 发布:虚拟社交网络语言规则 编辑:程序博客网 时间:2024/05/16 14:23

页面设计中,经常需要实现元素的水平垂直居中,css实现的方法有很多(列如: margin: auto、position定位、css表达式calc()、使用css预处理、table等都可以实现水平居中),但大多都是针对容器高度不固定,元素高度固定的情况。

这里我们介绍几种实现容器宽高和元素宽高都不固定的情况实现水平垂直居中

github代码片段地址: https://github.com/haozhaohang/library/tree/master/%E6%B0%B4%E5%B9%B3%E5%9E%82%E7%9B%B4%E5%B1%85%E4%B8%ADdemo

一、flex实现水平垂直居中

 1 <!DOCTYPE html> 2 <html> 3 <head> 4     <title>实现未知高度的垂直居中</title> 5  6     <style> 7         html, body { 8             height: 100%; 9         }10 11         .containers {12             width: 100%;13             height: 100%;14             display: flex;15             justify-content: center;16             align-items: center;17         }18     </style>19 20 </head>21 <body>22     <div class="containers">23         <span>flex实现垂直居中</span>24     </div>25 </body>26 </html>

容器设置display: flex;

容器内的元素设置 jusify-content: center;实现水平居中

        align-items: center; 实现垂直居中 

 

二、grid实现水平垂直居中(这可能是实现水平垂直居中最简单的css样式)

 1 <!DOCTYPE html> 2 <html> 3 <head> 4     <title>实现未知高度的垂直居中</title> 5  6     <style> 7         html, body { 8             height: 100%; 9         }10 11         .containers {12             height: 100%;13             display: grid;14         }15 16         span {17             margin: auto;18         }19     </style>20 21 </head>22 <body>23     <div class="containers">24         <span>grid实现垂直居中(许这是最简洁的水平垂直居中的 CSS 样式)</span>25     </div>26 </body>27 </html>

目前浏览器的支持率,但是可以用在内部的管理系统,在指定的浏览器上运行

容器设置 display: grid;

容器元素设置 margin: auto; 实现水平垂直居中