水平居中
内联元素
.center-text {
text-align: center;
}
块级元素
.center-box {
margin: 0 auto;
}
多块级元素
利用inline-block
如果一行中有两个或两个以上的块级元素,通过设置块级元素的显示类型为inline-block
和父容器的text-align
属性从而使多块级元素水平居中。
<div class="container">
<div class="inline-block">
</div>
<div class="inline-block">
</div>
<div class="inline-block">
</div>
</div>
.container {
text-align: center;
}
.inline-block {
display: inline-block;
}
利用flex
.flex-center {
display: flex;
justify-content: center;
}
垂直居中
单行内联元素
height: 120px;
line-height: 120px;
多行内联元素
利用表布局
利用表布局的vertical-align: middle
可以实现子元素的垂直居中。
.center-table {
display: table;
}
.v-cell {
display: table-cell;
vertical-align: middle;
}
利用flex布局
.center-flex {
display: flex;
flex-direction: column;
justify-content: center;
}
固定高度的块级元素
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
height: 100px;
margin-top: -50px;
}
未知高度的块级元素
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
水平垂直居中
已知宽度&绝对定位&margin负边距
<div class="box">
<div class="content">
</div>
</div>
.box {
position: relative;
width: 100px;
height: 100px;
background-color: red;
}
.content {
position: absolute;
width: 50px;
height: 50px;
padding: 10px;
background-color: blue;
left: 50%;
top: 50%;
margin: -35px 0 0 -35px;
}
已知宽度&绝对定位&margin : auto
<div class="box">
<div class="content">
</div>
</div>
.box {
position: relative;
width: 100px;
height: 100px;
background-color: red;
}
.content {
position: absolute;
width: 50px;
height: 50px;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
background-color: blue;
}
未知宽度&绝对定位&transform
<div class="box">
<div class="content">
</div>
</div>
.box {
position: relative;
width: 100px;
height: 100px;
background-color: red;
}
.content {
position: absolute;
width: 50px;
height: 50px;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background-color: blue;
}
flex布局
<div class="box">
<div class="content">
</div>
</div>
.box {
display: flex;
width: 100px;
height: 100px;
justify-content: center;
align-item: center;
background-color: red;
}
.content {
width: 50px;
height: 50px;
background-color: blue;
}
屏幕上水平垂直居中
常规的登录及注册页面用得到,要保证好的兼容性,还需要用到表布局。
table-cell布局
.outer {
display: table;
position: abslute;
width: 100%;
height: 100%;
}
.middle {
display: table-cell;
vertical-align: middle;
}