盒模型的上下左右居中

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

方法1:宽度和高度已知的。

.box{
            width: 400px;
            height: 200px;
            position: relative;
            background: red;
}
.child{
            width: 200px;
            height: 100px;
            background: #000;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left: -100px;
            margin-top: -50px;
}

方法2:兼容性最大

.box{
            width: 400px;
            height: 200px;
            position: relative;
            background: red;
}
.child{
            width: 200px;
            height: 100px;
            background: #000;
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            margin: auto;
}

3.flex

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

4.平移+定位

.box{
            width: 400px;
            height: 200px;
            position: relative;
            background: red;
}
.child{
            width: 200px;
            height: 100px;
            background: #000;
           position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%,-50%);
}

5.table-cell

.box{
            width: 400px;
            height: 200px;
            position: relative;
            background: red;
            display: table-cell;
            vertical-align: middle;
}
.child{
            width: 200px;
            height: 100px;
            background: #000;
            margin: 0 auto;
}

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

相关阅读更多精彩内容

友情链接更多精彩内容