css不定宽元素怎么水平居中?

css不定宽元素怎么水平居中?下面本篇文章给大家介绍一下使用CSS设置不定宽元素水平居中的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

css不定宽元素怎么水平居中?

公共代码:

html:

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

css:

html, body {
    margin: 0;
    width: 100%;
    height: 100%;
 
    .parent {
        width: 100%;
        height: 100%;
        background: #fac3fa;
         
        .child {
            width: 50%;
            height: 50%;
            background: #fe9d38;
        }
    }
}

方案一: text-align(父) + inline-block(子)

代码:

css:

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

方案二: absolute + transform

.parent {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
}

方案三: flex

注: 由于使用flex的关系, 这里去掉了 parent 和<br>

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

更多web前端开发知识,请查阅 HTML中文网 !!

以上就是css不定宽元素怎么水平居中?的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » CSS3 答疑