CSS盒模型的几种居中方式

css实现盒子模型居中方式

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

1.绝对定位 margin负值

.parent{
    width:600px;
    height:600px;
    margin:auto;
    position: relative;
    background-color: #000;
 }
.child{
    width:200px;
    height:200px;
    background-color: red;
    position: absolute;
    top:50%;
    left:50%;
    margin:-100px 0 0 -100px;
}

2.绝对定位 四个方位为0

.parent{
    width:600px;
    height:600px;
    margin:auto;
    position: relative;
    background-color: #000;
}
.child{
    width:200px;
    height:200px;
    background-color: red;
    position: absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    margin:auto;
}

3.绝对定位 translate

.parent{
    width:600px;
    height:600px;
    margin:auto;
    position: relative;
    background-color: #000;
}
.child{
    width:200px;
    height:200px;
    background-color: red;
    position: absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%)
}

4.margin属性居中

.parent{
    width:600px;
    height:600px;
    margin:auto;
        overflow: hidden;
    background-color: #000;
}
.child{
    width:200px;
    height:200px;
    background-color: red;
    margin: 150px auto 0;
}

5.table-cell

.parent{
    width:600px;
    height:600px;
        background-color: #000;
        display: table-cell;
        vertical-align: middle;
}
.child{
    width:200px;
    height:200px;
    background-color: red;
    margin: 0 auto;
}

6.flex 居中

.parent{
    width:600px;
    height:600px;
        display: flex;
        justify-content: center;
        align-items: center;
    background-color: #000;
    margin:0 auto;
}
.child{
    width:200px;
    height:200px;
    background-color: red;

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

相关阅读更多精彩内容

友情链接更多精彩内容