4种常用方法实现css水平垂直居中

125 阅读1分钟

水平垂直居中

方法1 绝对定位加margin:auto

<div class="box">
    <div class="child"></div>
</div>
	
.box{
    width: 100vw;
    height: 100vh;
    background-color: antiquewhite;
	/* 父元素设置相对定位 */
    position: relative;
}
.child{
    width: 200px;
    height: 100px;
    background-color: gold;
	/* 自身绝对定位 设置上下左右偏移值为0 margin: auto */
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
}

方法2 绝对定位配合负margin

.box{
    width: 100vw;
    height: 100vh;
    background-color: antiquewhite;
	/* 相对定位 */
    position: relative;
}
.child{
    width: 200px;
    height: 100px;
    background-color: gold;
	/* 绝对定位 设置偏移值top和left为50% 外边距margin上下为自身高度的一般,左右为自身宽度的一半 */
    position: absolute;
    top:50%;
    left:50%;
    margin: -50px -100px;
}

方法3 绝对定位配合transform

.box{
    width: 100vw;
    height: 100vh;
    background-color: antiquewhite;
    /* 相对定位 */
    position: relative;
}
.child{
    width: 200px;
    height: 100px;
    background-color: gold;
    /* 绝对定位 设置偏移值top和left为50% transform: translate中设置两个 -50% */
    position: absolute;
    top:50%;
    left:50%;
    transform: translate(-50%,-50%)
}

方法4 flex布局

.box{
    width: 100vw;
    height: 100vh;
    background-color: antiquewhite;
    /* display: flex */
    display: flex;
    justify-content: center;/*水平居中*/
    align-items: center;/*垂直居中*/
}
.child{
    width: 200px;
    height: 100px;
    background-color: gold;
}