div 居中

Posted studysuper

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了div 居中相关的知识,希望对你有一定的参考价值。

方法1 margin

.box{
    width: 100px;
    height: 100px;
    background-color: red;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -50px;
    margin-top: -50px;
}           

方法2 CSS3 transform-translate

.box {
    width: 100px;
    height: 100px;
    background-color: red;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

方法3 flex

.box {
    display: flex;
    background-color: red;
    height: 400px;
    width: 400px;
    align-items: center;
    justify-content: center;
}

.box2 {
    height: 100px;
    width: 100px;
    background-color: pink;
}

<div class="box">
    <div class="box2">
    </div>
</div>

方法4 转换为inline

.box {
    background-color: red;
    height: 400px;
    width: 400px;
    text-align: center;
    line-height: 400px;
}

.box2 {
    display: inline;
    background-color: pink;
}
<div class="box">
    <div class="box2">
        内容内容
    </div>
</div>

以上是关于div 居中的主要内容,如果未能解决你的问题,请参考以下文章