美文网首页
css实现水平垂直居中的几种方法

css实现水平垂直居中的几种方法

作者: spencer_sun | 来源:发表于2020-06-02 11:09 被阅读0次

1 flex布局法

html

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

scss

.box {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    div {
        width: 100px;
        height: 100px;
        background-color: #c1cbd7;
    }
}

结果展示


Screen Shot 2020-06-02 at 10.45.50 AM.png Screen Shot 2020-06-02 at 10.46.05 AM.png

2 position:absolute +负数 margin 或者transform

   <div class="container">
        <div class="box">
            <div></div>
        </div>
    </div>
.box {
    position: relative;
    width: 100%;
    height: 100%;
    div {
        width: 100px;
        height: 100px;
        background-color: #cccccc;
        position: absolute;
        left: 50%;
        top: 50%;
        // margin-left: -50px;
        // margin-top: -50px;
        transform: translate(-50%, -50%); // transform:translate 或者margin设置二者选一
    }
}

结果展示


Screen Shot 2020-06-02 at 10.45.50 AM.png Screen Shot 2020-06-02 at 10.46.05 AM.png

3 position:absolute + cal 定位

    <div class="container">
        <div class="box">
            <div></div>
        </div>
    </div>
.box {
    position: relative;
    width: 100%;
    height: 100%;
    div {
        width: 100px;
        height: 100px;
        background-color: #cccccc;
        position: absolute;
        top: calc(50% - 50px);
        left: calc(50% - 50px);
    }
}

结果


Screen Shot 2020-06-02 at 10.45.50 AM.png Screen Shot 2020-06-02 at 10.46.05 AM.png

相关文章

网友评论

      本文标题:css实现水平垂直居中的几种方法

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