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

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

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

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%ADdemogit

1、flex实现水平垂直居中github

 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;实现水平居中flex

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

 

2、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>

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

容器设置 display: grid;htm

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

相关文章
相关标签/搜索