Css对元素实现垂直水平居中

145 阅读2分钟

以下是对元素实现垂直水平居中的方式,亲测有效

方法一:利用transform+position

先假设有一个需要定位的div元素,并且设置了其宽高和背景色,添加其类名为box,那么实现其垂直水平居中的代码如下:

.box{
    width:200px;
    height:200px;
    background:red;
    /*这里定位用absolute还是relative取决于目标元素是否有父级元素,
    若有则定位用relative,此时垂直水平居中是在父级元素中实现*/
    position:absolute;
    left:50%;
    top:50%;
    transform:translate(-50%,-50%);
}

方法二:flex+margin

这种方法需要对根元素(也可以是父级元素)进行设置:

body,html{
    width:100%;
    height:100%;
    display:flex;
}
.box{
    width:200px;
    height:200px;
    background:red;
    margin:auto;
}

方法三:flex布局

body,html{
    /*必须给父元素设置高度,不然不会生效*/
    height:100%;
    display:flex;
    justify-content:center;
    align-items:center;
}

方法四:table-cell+margin

这种布局需要一个父级元素作为参考,假设存在一个类名为out的父级元素,则布局方案如下:

.out{
    width:400px;
    height:400px;
    display:table-cell;
    vertical-align:middle;
}
.box{
    width:200px;
    height:200px;
    background:red;
    margin:auto;
}

方法五:父元素相对定位,子元素绝对定位

.out{
    width:600px;
    height:600px;
    background:blue;
    position:relative;
}
.box{
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    margin:auto;
    width: 100px;
    height: 100px;
    background-color: mediumaquamarine;
}

方法六:负外边距

子元素设置margin为自身宽度和高度的一半

.out{
    width:600px;
    height:600px;
    position:relative;
    background:blue;
}
.box{
    position:absolute;
    top:50%;
    left:50%;
    margin:-50px;
    width: 100px;
    height: 100px;
    background-color: mediumaquamarine;
}

方法七:grid布局

会有兼容性问题

.out{
    width:600px;
    height:400px;
    dislay:grid;
    background:blue;
}
.box{
    width:200px;
    height:200px;
    background:red;
    align-self:center;
    justify-self:center;
}

以上就是实现垂直水平居中比较有效的方式了,如果还有更好的更有效的方案,欢迎评论区讨论