目录
css
水平垂直居中
position
定位实现
父元素
.parent {
background-color: red;
width: 600px;
height: 600px;
position: relative;
}
子元素,需设置宽高,margin-left| margin-top|
自身宽高的一半
.child {
background-color: yellow;
width: 500px;
height: 500px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -250px;
margin-left: -250px;
}
子元素,需设置宽高
.child2 {
background-color: pink;
width: 400px;
height: 400px;
position: absolute;
margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
子元素,需设置宽高
css3
的计算属性calc
.child3 {
background-color: green;
width: 300px;
height: 300px;
position: absolute;
top: calc(50% - 150px);
left: calc(50% - 150px);
}
子元素,不需设置宽高
.child4 {
background-color: deepskyblue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
flex
实现
父元素使用了弹性盒模型 display: flex
并且设置了弹性盒模型里面的元素水平方向上居中 justify-content: center
,垂直方向上居中 align-items: center
,因此里面的元素会水平垂直居中对齐
.parent2 {
background-color: palevioletred;
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
}
display
实现
父元素,里面的元素(除float、position:absolute
)都会水平垂直居中
.parent3{
background-color: gold;
height: 300px;
width: 300px;
display: table-cell;
text-align: center;
/*在Flex布局中,flex子元素的设置float,clear以及vertical-align属性都是没有用的。*/
vertical-align: middle;
}
参考
利用CSS中display:table/table-cell可以解决大部分垂直居中、多列等高、自适应布局