CSS解决网页HTML元素DIV等无法居中的方法

710 阅读1分钟

1.水平居中

<div class="box"></div>
 
.box{
    width: 100px;
    height: 100px;
    margin: 0 auto;
    background: #E33;
}

2.水平垂直居中

(1)绝对定位水平垂直居中

<div class="box">
     <div></div>
</div>
 
.box {
    width: 100%;
    height: 500px;
    background: #e33;
    position: relative;
}
.box>div{
    width: 100px;
    height: 100px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    background: gold;
}

(3)flex弹性布局垂直水平居中

<div class="box">
   <div></div>
</div>
 
.box {
    width: 100%;
    height: 500px;
    background: #e33;
    display: flex;
    align-items: center;
    justify-content: center;
}
.box>div{
    width: 100px;
    height: 100px;
    background: gold;
}