水平居中
发布于
# CSS
text-align
<div>
<p>
7777 777777777 777777777777 77777 7777 77777 77777 7777 77777 7777777 7777 777777 77777 7777 777777 7777 777 777 77 7 7777 7777
</p>
</div>
div:nth-of-type(1) {
text-align: center;
}
优点:兼容性好 缺点:只对行内元素有效;属性会影响到后续内容;子元素的宽度必须小于父元素
绝对定位
<div>
<p>
7777 777777777 777777777777 77777 7777 77777 77777 7777 77777 7777777 7777 777777 77777 7777 777777 7777 777 777 77 7 7777 7777
</p>
</div>
div:nth-of-type(1) {
position: relative;
}
div:nth-of-type(1) p {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
优点:不管是块级还是行内元素都可以实现 缺点:代码较多;脱离文档流;使用 transform 兼容性不好(ie9+)
margin
<div>
<p>
7777 777777777 777777777777 77777 7777 77777 77777 7777 77777 7777777 7777 777777 77777 7777 777777 7777 777 777 77 7 7777 7777
</p>
</div>
div:nth-of-type(1) {
width: 100px;
margin: 0 auto;
}
优点:兼容性好 缺点:必须设置宽度,子元素的宽度必须小于父元素
flex
<div>
<p>
7777 777777777 777777777777 77777 7777 77777 77777 7777 77777 7777777 7777 777777 77777 7777 777777 7777 777 777 77 7 7777 7777
</p>
</div>
div:nth-of-type(1) {
display: flex;
justify-content: center;
}
优点:大众主流;强大;简单 缺点:PC 端兼容性不好,移动端(Android4.0+)