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

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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。