基础拓展-元素水平垂直居中方法总汇

题例:
<body>
    <div class="box" style="width: 500px;height: 500px;">
        <div class="b" style="width: 100px;height: 100px;"><div>
    </div>  
</body>

1. 定位+自动外边距
.b{
    position:absolute;
    left:0;
    right:0;
    top:0;
    bottom:0;
    margin:auto;
}

2. 定位+负值外边距反推    [需要知道目标元素的宽高]
.b{
    position:absolute;
    top:50%;
    left:50%;
    margin:(-50px 0 0 -50px)
        [margin-top的数值为目标元素自身高度height负值的一半]
        [margin-left的数值为目标元素自身宽度width负值的一半]
}

3. 定位+2d变换

.b{
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(50% 50%)
}

4.弹性盒

.box{
    display:flex;
    justify-content:center;
    align-items:center;
}

5.行内块属性

<body>
    <div class="box" style="width: 500px;height: 500px;">
        <div class="b" style="width: 100px;height: 100px;"><div>
        <span></span>
            [在父元素中添加空白文本]
    </div>  
</body>
.box{
    line-height: 500px;
    text-align: center;
}
.b{
    display: inline-block;
    vertical-align: middle;
}

6. 网格布局的grid-area属性

.box{
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr 1fr;
    grid-template-areas: '. . .'
                         '. a .'
                         '. . .';
}
.b{
    grid-area: a;
}

7. 网格布局    [创造单个单元格]

.box{
    display: grid;
    grid-template-columns: 100px;
    grid-template-rows: 100px;
    justify-content: center;
    align-content: center;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容