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

页面设计中,经常需要实现元素的水平垂直居中,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; 实现水平垂直居中

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值