美文网首页
CSS水平居中

CSS水平居中

作者: wanghaoi | 来源:发表于2016-08-31 00:18 被阅读0次

假设html元素为下面这样,父容器和子容器的宽高均为不确定

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

下面四种方案对其水平居中
方案一: test-align+inline-block

.parent{
    text-align: center;
}
.child{
    display: inline-block;
}

优点:兼容性好;
缺点:text-align: center;会被child元素继承下来,需要额外的代码来修复.

方案二 margin+table

.child{
    display: table;
    margin:0 auto;
}

优点:只对child元素进行处理.

方案三 absolute+transform

.parent{
    position: relative;
}
.child{
    position: absolute;
    left:50%;
    transform: translateX(-50%);//参照物为自身
}

优点:脱离文档流,不会对其他元素产生影响;缺点:兼容性差.

方案四 flex+justify—content

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

优点:只对parent元素进行设置

相关文章

网友评论

      本文标题:CSS水平居中

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