不要屈从,不要流泪,不要试着合乎情理,不要为了媚俗而去改变你的灵魂;相反,果断地追随让你强烈痴迷的事物。——卡夫卡
在网页设计中,时常会有居中的样式需求。
居中,兼具汇聚、对称的美感。
而在前端开发中,通过css样式实现元素居中有多种方式。
水平居中(Center Horizontally)
1.行内级(内联)元素:
- 设置父级元素text-align属性为center。
2.块级元素:
- 设置当前块级元素(宽度) margin: 0 auto;
3.绝对定位
- 元素不知宽度情况下(或者不想考虑元素宽度), left: 0;right: 0; margin: 0 auto;
- 元素已知宽度可以,left: 50%; margin-left: 负值; (负值为元素宽度一半)
4.flex
- justify-content: center;
垂直居中(Center vertically)
“44 年前我们就把人类送上月球了,但现在我们仍然无法在 CSS 中 实现垂直居中。”
--Jams Anderson
1.行高(令单行文字垂直居中)
令line-height = 文字所在盒子高度,文字将垂直居中显示。
2.绝对定位
- 元素有高度情况下, top: 0;bottom: 0;margin: auto 0;
- 缺点:
(1) 必须使用定位(脱离标准流)。
(2) 需要给元素设置高度。
3.flex布局
align-items:center;
- 缺点: flex container中所有的元素都会垂直居中显示。
4.定位加形变 position/translate
分两步走
1.让需要居中的元素向下位移父级元素content高度的50%。
2.让需要居中的元素向上位移自身高度的50%。
margin-top的百分比是相对于包含块(父元素)的宽度。
margin-top: 50%; position: relative; top: 50%; transform: translate(0, -50%);`
其中水平居中的margin-left负值方案可换成margin-top负值使得垂直居中;
垂直居中的translate方案同样可用于水平居中。
更多方法总结参考