运行效果
HTML结构
<div class="container">
<div class="content"></div>
</div>
实现方式
1. 绝对定位 + margin:auto
思路:绝对定位使子元素脱离文档流,再将各方向定位值设置为0,由margin自动分配剩余空间,从而实现元素的水平垂直居中
.container {
width: 200px;
height: 200px;
background-color: skyblue;
position: relative;
}
.content {
width: 80px;
height: 80px;
background-color: pink;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
2. 绝对定位 + margin设为负值
前提条件:要已知子元素宽高
思路:先把块级元素中的左上角定位到父元素的中心( left:50%; top:50%; ),然后再向上向左偏移本身的一半( margin-left: width/2; margin-top: height/2; )
.container {
width: 200px;
height: 200px;
background-color: skyblue;
position: relative;
}
.content {
width: 80px;
height: 80px;
background-color: pink;
position: absolute;
left: 50%;
top: 50%;
margin-left: -40px;
margin-top: -40px;
}
3. 绝对定位 + transform属性
思路:与第二种相似,这样就不用知道子元素的宽高,直接用transform 的 translate 使子元素向上向左偏移自身宽、高的一半。
.container {
width: 200px;
height: 200px;
background-color: skyblue;
position: relative;
}
.content {
width: 80px;
height: 80px;
background-color: pink;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
4. 子元素自身相对定位 + transform属性
注意:此方法是相对于元素自身原本所处位置进行偏移,如果其父元素有多个同级子元素,则此方法不可行
.container {
width: 200px;
height: 200px;
background-color: skyblue;
}
.content {
width: 80px;
height: 80px;
background-color: pink;
position: relative;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
5. flex(弹性盒)布局
思路:将父元素设置为弹性盒,让其子元素 justify-content: center; 主轴居中;align-items: center; 侧轴居中
.container {
width: 200px;
height: 200px;
background-color: skyblue;
display: flex;
justify-content: center;
align-items: center;
}
.content {
width: 80px;
height: 80px;
background-color: pink;
}
6. flex + margin:auto;
思路:把父元素设置为弹性盒子,然后给子元素添加margin:auto; 完成元素的垂直水平居中
.container {
width: 200px;
height: 200px;
background-color: skyblue;
display: flex;
}
.content {
width: 80px;
height: 80px;
background-color: pink;
margin: auto;
}
7. table-cell布局(一)
思路:table-cell相当与表格的单元格td,而td为行内元素,无法设置宽和高,所以必须将其子元素设置display: inline-block; 此方法不推荐使用
.container {
width: 200px;
height: 200px;
background-color: skyblue;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.content {
width: 80px;
height: 80px;
background-color: pink;
display: inline-block;
}
8. table-cell布局(二)
父元素设置 display: table-cell; vertical-align: middle; 子元素设置 margin: auto;
注意:这种方式是让所有的子元素作为一个整体垂直居中,不能使其中的某个子元素单独垂直居中
.container {
width: 200px;
height: 200px;
background-color: skyblue;
display: table-cell;
vertical-align: middle;
}
.content {
width: 80px;
height: 80px;
background-color: pink;
margin: auto;
}
9. line-height
思路:text-align: center; 让文字水平居中,line-height: 父元素高度; 让单行文本垂直居中
注意:此方法仅适用于子元素为单行文本时
如果有其它实现方式,欢迎各位大佬补充,相互学习,共同进步!