CSS布局排版中,三种水平居中的方式。text-align, margin: auto; justify-content:center

text-align 属性规定元素中的文本的水平对齐方式。用来设置块级元素内文本的水平对齐方式。

margin在不同级别元素下不同的表现方式:块级元素的垂直相邻外边距会合并,而行内元素实际上不占上下外边距。行内元素的的左右外边距不会合并。同样地,浮动元素的外边距也不会合并。

margin:0 auto居中失效的几种情况:

1. 没有明确的width。所以没有设定宽度的块状元素,以及没有宽度的行内元素,都是无效的。

2. float:left或float:right 造成的样式冲突

3. 给一个元素设置了position: absolute, 未设置宽高。要让margin: auto产生作用的代码,比如这样:

        .div1{
            width: 500px;
            background-color: red;
            height: 200px;
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            margin: auto;
        }

为什么要这样呢。看CSS 2.1原文:

The constraint that determines the used values for these elements is:

'left' + 'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' + 'right' = width of containing block

If none of the three is 'auto': If both 'margin-left' and 'margin-right' are 'auto', solve the equation under the extra constraint that the two margins get equal values [...]

在这种情况下,margin: 0 auto对于绝对定位元素和非绝对定位的元素,所起的作用没有差别。

3. margin 只对非文本的块状元素产生作用?参照第一条规则,试验了 img、p标签和span标签分别包裹的文字,文字要设定宽度(不设置宽度就会占满整行),img要设置 display: block。但是对于文字和图片来说,其实用text-align: center,不是更好么。

3. 对body设置text-align:center,以便兼容低版本和高版本浏览器

4. 对最外层DIV设置margin:0 auto,兼容各大浏览器水平居中样式

当然,以上终于发现我今天的DEMO里,凡是img,不管有没用div包裹,margin: 0 auto 不起作用的问题,最后只好用 flex布局的 justify-content: center 来实现水平居中。

以上三者,margin作用于元素本身,而text-align 和  justify-content 作用于子元素。

最后。关于flex布局。一定要注意其属性默认值。一不小心又是一个坑。

原文地址:https://www.cnblogs.com/dodocie/p/7065629.html