Position(定位)
利用相对定位来让盒子垂直居中
/* CSS代码: */
/* 框架 */
.wrap{
width: 600px;
height: 600px;
border: 2px solid black;
/* 设置为相对定位,用来作为绝对定位元素的容器块。 */
position: relative;
}
/* 盒子 */
.box{
width:50px;
height: 50px;
background-color: red;
/* 设置为绝对定位,在相对定位的容器下定位 */
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
/* html代码: */
/* wrap为box盒子的框架 */
<div class="wrap">
<div class="box">
</div>
</div>
实现效果:
表格
将框架设置成表格元素,让表格子元素垂直居中
/* CSS代码: */
.wrap{
width: 600px;
height: 600px;
border: 2px solid black;
/* 设置成表格单元格 */
display: table-cell;
/* 使文字垂直居中 */
vertical-align: middle;
}
.box{
width:50px;
height: 50px;
background-color: red;
/* 水平居中 */
margin:auto;
/* html代码: */
<div class="wrap">
<div class="box">
</div>
</div>
实现效果:
弹性布局
将框架设置为弹性布局
/* CSS代码: */
.wrap{
width: 600px;
height: 600px;
border: 2px solid black;
/* 设置为弹性布局 */
display: flex;
/* 子元素在主轴对齐方式为居中 */
justify-content: center;
/* 交叉轴在y轴对齐 */
align-items: center;
}
.box{
width:50px;
height: 50px;
background-color: red;
/* html代码: */
<div class="wrap">
<div class="box">
</div>
</div>
实现效果:
Position + Transform
/* CSS代码: */
.wrap{
width: 600px;
height: 600px;
border: 2px solid black;
/* 设置为相对定位,用来作为绝对定位元素的容器块。 */
position: relative;
}
.box{
width:50px;
height: 50px;
background-color: red;
/* 设置为绝对定位,位置在父容器的中心 */
position: absolute;
margin: auto;
left: 50%;
top:50%;
/* 向回移动自身一半的长宽 */
transform: translateX(-50%) translateY(-50%);
}
/* html代码: */
<div class="wrap">
<div class="box">
</div>
</div>
实现效果:
inline-block
/* CSS代码: */
.wrap{
width: 600px;
border: 2px solid black;
/* 设置行高为600px */
line-height: 600px;
/* 让子盒子水平居中 */
text-align: center;
}
.box{
height: 50px;
width: 50px;
/* 设置为块级元素 */
display: inline-block;
/* 设置为垂直居中 */
vertical-align: middle;
background-color: red;
}
/* html代码: */
<div class="wrap">
<div class="box">
</div>
</div>
实现效果: