实现一个元素水平垂直居中的方法很多:
- 元素未知宽高
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 }
感谢阅读,欢迎大家来吐糟。
纯CSS-元素水平垂直居中之fit-content布局
原文地址:https://www.cnblogs.com/belongto/p/8295364.html