实现一个元素水平垂直居中的方法很多:
元素未知宽高
width 和 height 的 fit-content 值只支持 Chrome 和 Firefox 浏览器
元素已知宽高
.box {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
width: fit - content;
width: -webkit - fit - content;
width: -moz - fit - content;
height: fit - content;
height: -webkit - fit - content;
height: -moz - fit - content;
overflow: hidden;
text - align: center;
background - color: #eee;
}
大家对这个应该是很了解的,也是实际开发中运用最多的,推荐给刚刚入门的小伙伴吧.
设置它的父元素为 position:relative 即可:
第一种方式:
第二种方式:
.children {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: 300px;
height: 200px;
background - color: #5f9a3f;
}
第三种方式:
.children {
position: absolute;
top: 50 % ;
left: 50 % ;
margin: -100px 0 0 - 150px;
width: 300px;
height: 200px;
background - color: #5f9a3f;
}
使用 CSS3 新属性 transform 的 translate 属性
.children {
position: absolute;
top: 50 % ;
left: 50 % ;
transform: translate( - 50 % , -50 % );
width: 300px;
height: 200px;
background - color: #5f9a3f;
}
来源: http://www.bubuko.com/infodetail-2463094.html