美文网首页
margin:0 auto 和text-align:center

margin:0 auto 和text-align:center

作者: 夜未央_M | 来源:发表于2018-10-22 01:22 被阅读6次
margin 是指当前元素到相邻元素间的距离。
text-align 指当前元素中内容的对其方式。

通常情况下 text-align: center 的方式就可以满足居中对齐的方式,但页面布局时存在两个特殊情况:position: absolute 和 position: fixed,这两种情况下的元素会脱离布局流,而导致无法正确居中,这时如要使其居中,需要配合多个 css 属性使用:

.abc {
    position: absolute;
    width: 500px;
    right: 0;
    left: 0;
    margin: auto;
}

如需附加垂直对齐,可添加 height、top、bottom。

另:

当 position: absolute 时,元素会向父级递归寻找 position 属性不为 static 的元素,并找到的第一个元素的边界为基准进行居中对齐,如果找不到,则以 body 元素为基准。

当 position: fixed 时,元素以浏览器的窗口为基准居中对齐。

margin:0 auto;是使自身在浏览器内居中,需要配合宽度使用:

<div stley="width:500px;height:200px;border:1px solid #000000;margin:0 auto;">
使用margin:0 auto;后不要设置float:left和right,否则会失效
</div>

text-align:center;是使标签的内容居中:

<div stley="width:500px;height:200px;border:1px solid #000000;margin:0 auto;text-align:center;">
使用text-align:center;后,此div中的内容会居中
</div>

相关文章

网友评论

      本文标题:margin:0 auto 和text-align:center

      本文链接:https://www.haomeiwen.com/subject/iefwzftx.html