CSS水平垂直居中的几种方法总结

190 阅读1分钟

CSS水平垂直居中的几种方法总结

方法1、利用 flex 弹性布局

通过给父元素设置display:flex,在设置justify-content: center; //主轴居中 align-items: center; //侧轴居中

.father{
        display: flex;
        justify-content: center; //主轴
        align-items: center; //侧轴
        background-color: pink;
        width: 200px;
        height: 200px;
    }
    .son{
        background-color: red;
        width: 50px;
        height: 50px;
    }

方法2、利用定位:子绝父相

背景代码:

<div class="father">
     <div class="son"></div>
</div>

情况1:当已知元素宽度和高度时,可以设置position: absolutemargin为负的宽高的一半

<style>
    .father{
        position: relative;
        background-color: pink;
        width: 200px;
        height: 200px;
    }
    .son{
        position: absolute;
        background-color: red;
        width:50px;
        height: 50px;
        left: 50%;
        top: 50%;
        margin-top: -25px;
        margin-left: -25px;
    }
</style>

情况2:当元素宽度和高度未知时,可以设置position: absolutetransform: translate(-50%, -50%)

.father{
        position: relative;
        background-color: pink;
        width: 200px;
        height: 200px;
    }
    .son{
        position: absolute;
        width: 50px;
        height: 50px;
        background-color: red;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
    }

方法3、利用子绝父相定位的 margin:auto

利用定位:子绝父相,再对子元素设置left: 0; top: 0; right: 0; bottom: 0; margin: auto;

.father{
        position: relative;
        background-color: pink;
        width: 200px;
        height: 200px;
    }
    .son{
        position: absolute;
        background-color: red;
        width: 50px;
        height: 50px;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        margin: auto;
    }

方法4、利用水平对齐和行高

设置text-align:centerline-height:height实现单行文本水平垂直居中

<div class="father">
     <div class="son">待居中文本</div>
</div>
.father{
        background-color: pink;
	width: 200px;
	height: 200px;
	text-align: center;
}
.son{
	line-height: 200px;
}