前言:如何让一个块级子元素在父元素当中水平垂直居中?有几种实现方法?这是一道非常高频的CSS面试题,本文接下来谈一下实现的几种方法。 首先给大家展示一下嵌套关系,接下来的实现代码将以此为基础。
一、父元素弹性盒模型
给父元素加弹性盒属性,加justify-content , align-items
属性即可
.father {
border: solid 1px;
width: 300px;
height: 300px;
display: flex; /*开启弹性盒*/
justify-content: center; /*水平居中*/
align-items: center; /*垂直居中*/
}
.son {
background: #e4393c;
width: 100px;
height: 100px;
}
二、父元素弹性盒,子元素margin:auto
给父元素加弹性盒属性,子元素加 margin:auto
即可
.father {
border: solid 1px;
width: 300px;
height: 300px;
display: flex; /*开启弹性盒*/
}
.son {
background: #e4393c;
width: 100px;
height: 100px;
margin: auto;
}
三、定位,父相子绝,配合transform属性
给父元素加相对定位,给子元素加绝对定位,并且使用transform
平移实现
.father {
border: solid 1px;
width: 300px;
height: 300px;
position: relative;
}
.son {
background: #e4393c;
width: 100px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);/* 参考自己的位置向上向左各平移自身的50% */
}
四、定位,父相子绝,配合margin属性
父元素相对定位,子元素绝对定位同时上下左右为0,同时加上margin:auto
.father {
border: solid 1px;
width: 300px;
height: 300px;
position: relative;
}
.son {
background: #e4393c;
width: 100px;
height: 100px;
position: absolute;
margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
五、父元素display: table-cell,子元素display: inline-block;
将父元素转为一个表格单元,子元素转为行内块
.father {
border: solid 1px;
width: 300px;
height: 300px;
display: table-cell; /*此元素会作为一个表格单元格显示(类似 <td> 和 <th>)*/
text-align: center; /*水平居中*/
vertical-align: middle; /*垂直居中*/
}
.son {
background: #e4393c;
width: 100px;
height: 100px;
display: inline-block; /*将其转为行内块元素*/
}
六、简单粗暴的纯定位方式实现
父相子绝,子元素 left , right
各50%,再使用 margin-left , margin-top
, 移动子元素自身宽高的一半
.father {
border: solid 1px;
width: 300px;
height: 300px;
position: relative;
}
.son {
background: #e4393c;
width: 100px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
总结一下,比较常用的方法就是 第一、二种,如果PC端需要考虑兼容的话,可以使用第六种,其他的大家可以作为一个扩展了解一下。
最后大家如果觉得写的还可以的话就给个赞吧,谢谢。