一、内联元素(inline)
1、水平居中
// 对父级盒子设置
text-align: center;
2、垂直居中
// 对子级元素设置
line-height: $height; // $height为父级盒子的高度
3. 水平垂直居中
HTML:
<div class="father">
<span class="son">内联元素</span>
</div>
CSS:
.father {
width: 200px;
height: 50px;
text-align: center; // 水平居中
background-color: red;
}
.son {
color: #fff;
line-height: 50px; // 垂直居中
}
运行结果:
二、内联块状元素 (inline-block)
1、水平居中
// 对父级盒子设置
text-align: center;
2、垂直居中
// 子级元素
vertical-align: middle;
3、水平垂直居中
HTML:
<div class="father">
<span class="son"></span>
</div>
CSS:
.father {
width: 300px;
height: 100px;
line-height: 100px;
text-align: center; // 水平居中
background-color: red;
}
.son {
display: inline-block;
width: 100px;
height: 50px;
vertical-align: middle; // 垂直居中
background-color: yellow;
}
三、块状元素(block)
1、水平居中
// 给子级元素设置
margin: 0 auto;
2.水平垂直居中(可根据代码总结垂直居中)
(1)position + margin
// 对父级设置
position: relative;
// 对子级设置
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto; // 自适应上下左右的间距
代码如下:
HTML:
<div class="father">
<div class="son"></div>
</div>
CSS:
.father {
position: relative;
width: 300px;
height: 300px;
background-color: red;
}
.son {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
width: 100px;
height: 100px;
background-color: yellow;
}
(2)position + transform
// 对父级设置
position: relative;
// 对子级设置
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); // 向上向左平移自身的一半
代码如下:
HTML:
<div class="father">
<div class="son"></div>
</div
CSS:
.father {
position: relative;
width: 300px;
height: 300px;
background-color: red;
}
.son {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100px;
height: 100px;
background-color: yellow;
}
四:使用 display:flex 实现各类元素水平垂直居中
// 对父级盒子设置
display: flex;
justify-content: center; // 内容 X 轴居中对齐
align-items: center; // 内容 Y 轴居中对齐
代码如下:
HTML:
<div class="father">
<div class="son"></div>
</div
CSS:
.father {
display: flex;
justify-content: center;
align-items: center;
width: 300px;
height: 300px;
background-color: red;
}
.son {
width: 100px;
height: 100px;
background-color: yellow;
}
上述代码运行效果如图: