css實現盒子模型的各類居中方式

<div class="parent">
    <div class="child"></div>
</div>
複製代碼

1.絕對定位 margin負值flex

.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.絕對定位 四個方位爲0spa

.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.絕對定位 translatecode

.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屬性居中orm

.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-cellcdn

.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 居中blog

.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;
    
}
複製代碼

總結了下用6種方法實現盒子居中的方式。純當我的積累了^.^it

相關文章
相關標籤/搜索