CSS水平垂直居中之fit-content布局

实现一个元素水平垂直居中的方法很多:

  • 元素未知宽高

width和height的fit-content值只支持Chrome和Firefox浏览器

 1 .box {
 2     position: absolute;
 3     top: 0;
 4     left: 0;
 5     bottom: 0;
 6     right: 0;
 7     margin: auto;
 8     width: fit-content;
 9     width: -webkit-fit-content;
10     width: -moz-fit-content;
11     height: fit-content;
12     height: -webkit-fit-content;
13     height: -moz-fit-content;
14     overflow: hidden;
15     text-align: center;
16     background-color: #eee;
17 }
  • 元素已知宽高

大家对这个应该是很了解的,也是实际开发中运用最多的,推荐给刚刚入门的小伙伴吧。

设置它的父元素为position:relative即可:

第一种方式:

 1 .children{
 2     position: absolute;
 3     top: 0;
 4     bottom: 0;
 5     left: 0;
 6     right: 0;
 7     margin: auto;
 8     width: 300px;
 9     height: 200px;
10     background-color: #5f9a3f;
11 }

第二种方式:

1 .children{
2     position: absolute;
3     top: 50%;
4     left: 50%;
5     margin: -100px 0 0 -150px;
6     width: 300px;
7     height: 200px;
8     background-color: #5f9a3f;
9 }

第三种方式:

使用CSS3新属性transform的translate属性

1 .children{
2     position: absolute;
3     top: 50%;
4     left: 50%;
5     transform: translate(-50%,-50%);
6     width: 300px;
7     height: 200px;
8     background-color: #5f9a3f;
9 }

感谢阅读,欢迎大家来吐糟。

 

转载于:https://www.cnblogs.com/belongto/p/8295364.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值