.parent {
text-align: center;
}
复制代码
.son {
margin: 0 auto;
}
复制代码
.parent{
width:fit-content;
margin:0 auto;
}
.son {
float: left;
}
复制代码
1) flex 2012版css
.parent {
display: flex;
justify-content: center;
}
复制代码
2)flex 2009版segmentfault
.parent {
display: box;
box-orient: horizontal;
box-pack: center;
}
复制代码
1)transform浏览器
.son {
position: absolute;
left: 50%;
transform: translate(-50%, 0);
}
复制代码
2)left: 50%bash
.son {
position: absolute;
width: 宽度;
left: 50%;
margin-left: -0.5*宽度
}
复制代码
3)left/right: 0布局
.son {
position: absolute;
width: 宽度;
left: 0;
right: 0;
margin: 0 auto;
}
复制代码
以上是 CSS 水平居中的 8 种方法。post
.parent {
height: 高度;
}
.son {
line-height: 高度;
}
复制代码
注:① 子元素 line-height 值为父元素 height 值。② 单行文本。flex
.parent::after, .son{
display:inline-block;
vertical-align:middle;
}
.parent::after{
content:'';
height:100%;
}
复制代码
适应 IE7。ui
.parent {
display: table;
}
.son {
display: table-cell;
vertical-align: middle;
}
复制代码
优势spa
缺点3d
1)flex 2012版
.parent {
display: flex;
align-items: center;
}
复制代码
优势
缺点
2)flex 2009版
.parent {
display: box;
box-orien: vertical;
box-pack: center;
}
复制代码
优势
缺点
1)transform
.son {
position: absolute;
top: 50%;
transform: translate( 0, -50%);
}
复制代码
优势
缺点
2)top: 50%
.son {
position: absolute;
top: 50%;
height: 高度;
margin-top: -0.5高度;
}
复制代码
优势
缺点
3)top/bottom: 0;
.son {
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
}
复制代码
优势
缺点
以上是 CSS 垂直居中的 8 种方法及其优缺点。
其中,
同时适用于水平居中和垂直居中。
但愿帮助到了你。
欢迎讨论。
٩(๑❛ᴗ❛๑)۶
感谢@ape-casear,@斗鹰 的指正!
也欢迎你们一块儿将 CSS 的居中总结得更好!
参考文献
[1] louis. 16种方法实现水平居中垂直居中[OL],2017-04-20.
[2] 慢思考快行动. css设置垂直居中[OL], 2017-09-03.