水平居中的五种方法及其优缺点

xiaoxiao2021-02-28  94

<div class="parent"> <div class="child">test</div> </div>

第一种:

.parent{ text-align: center; } .child{ display: inline-block; }优点:代码少,兼容性好  inline-block ie6-7不兼容(可用inline+zooom:1)

缺点:text-align 会将文字移动,有时需text-align:left解决;

第二种:

.child{ display: table; margin: 0 auto; }优点:兼容性好 IE8及以上,不影响父元素

缺点:IE6-7不支持(需将HTML变为table结构)

第三种:

.parent{ position: relative; } .child{ position: absolute; left: 50%; transform: translate(-50%); } 优点:不定宽

缺点: 兼容性不好

第四种:

.parent{ display: flex; justify-content: center; }

优点:简洁

缺点:兼容性不好

第五种:

.parent{ display: flex; } .child{ margin:0 auto; }

优点:简洁

缺点:兼容性不好

转载请注明原文地址: https://www.6miu.com/read-60936.html

最新回复(0)