水平居中元素:
方式一:CSS3 transform
.parent {
? ? position: relative;
}
.child {
? ? position: absolute;
? ? left: 50%:
? ? transform: translateX(-50%);
}
方式二:flex 布局
.parent {
? ? display: flex;
? ? justify-content: center;
}
適用于子元素為浮動,絕對定位,內聯元素,均可水平居中。
居中的元素為常規文檔流中的內聯元素(display: inline)
常見的內聯元素有:span, a, img, input, label 等等
.parent {
? ? text-align: center;
}
居中的元素為常規文檔流中的塊元素(display: block)
常見的塊元素:div, h1~h6, table, p, ul, li 等等
方式一:設置 margin
.parent {
? ? width: 100%;
}
.child {
? ? width: 600px;
? ? height: 50px;
? ? margin: 0 auto;
? ? background: #999;
}
方式二:修改為 inline-block 屬性
.parent {
? ? text-align: center;
}
.child {
? ? display: inline-block;
}
.child {
? ? width: 100px;
? ? float: left;
? ? position: relative;
? ? left: 50%;
? ? margin-left: -50px;
}
方式一:
.parent {
? ? position: relative;
}
.child {
? ? position: absolute;
? ? width: 100px;
? ? left: 50%;
? ? margin-left: -50px;
}
方式二:
.parent {
? ? position: relative;
}
.child {
? ? position: absolute;
? ? width: 100px;
? ? left: 0;
? ? right: 0;
? ? margin: 0 auto;
}
垂直居中元素:
方式一:CSS3 transform
.parent {
? ? position: relative;
}
.child {
? ? position: absolute;
? ? top: 50%;
? ? transform: translateY(-50%);
}
方式二:flex 布局
.parent {
? ? display: flex;
? ? align-items: center;
}
適用于子元素為浮動,絕對定位,內聯元素,均可垂直居中。
.text {
? ? line-height: 200px;
? ? height: 200px;
}
方式一:
.parent {
? ? position: relative;
}
.child{
? ? position: absolute;
? ? top: 50%;
? ? height: 100px;
? ? margin-top: -50px;
}
方式二:
.parent {
? ? position: relative;
}
.child{
? ? position: absolute;
? ? top: 0;
? ? bottom: 0;
? ? height: 100px;
? ? margin: auto 0;
}
垂直居中元素:
div {
? ? width: 100px;
? ? height: 100px;
? ? margin: auto;
? ? position: fixed;
? ? //absolute is ok
? ? top: 0;
? ? right: 0;
? ? bottom: 0;
? ? left: 0;
}
優點:
不僅可以實現在正中間,還可以在正左方,正右方
元素的寬高支持百分比 % 屬性值和 min-/max- 屬性
可以封裝為一個公共類,可做彈出層
瀏覽器支持性好
.child {
? ? width: 100px;
? ? height: 100px;
? ? position: absolute;
? ? top: 50%;
? ? left: 50%;
? ? margin-left: -50px;
? ? margin-top: -50px;
}
特點:
良好的跨瀏覽器特性,兼容 IE6 - IE7
靈活性差,不能自適應,寬高不支持百分比尺寸和 min-/max- 屬性
.child {
? ? width: 100px;
? ? height: 100px;
? ? position: absolute;
? ? top: 50%;
? ? left: 50%;
? ? transform: translate(-50%, -50%);?
}
特點:
內容可自適應,可以封裝為一個公共類,可做彈出層
可能干擾其他 transform 效果
.parent {
? ? display: flex;
? ? justify-content: center;
? ? align-items: center;
}
這是 CSS 布局未來的趨勢。Flexbox 是 CSS3 新增屬性,設計初衷是為了解決像垂直居中這樣的常見布局問題。
text {
? ? height: 100px;
? ? line-height: 100px;
? ? text-align: center;
}
原文:https://zhuanlan.zhihu.com/p/25068655