初始HTML代码如下:
<div class="father">
<div class="son"></div>
</div>
初始CSS代码如下:
.father {
width: 300px;
height: 300px;
background-color: pink;
margin: 20px auto;
}
.son {
width: 100px;
height: 100px;
background-color: blue;
}
初始效果图如下:
垂直居中方法如下:
- 使用子盒子与父盒子的外边距margin控制垂直方向位置
.father {
overflow: hidden;/*触发BFC,避免父子元素外边距合并*/
}
.son {
margin-top: 100px; /*外边距控制垂直方向位置*/
}
- 定位
.father {
position: relative; /*定位*/
}
.son {
position: absolute;
top: 50%;
transform: translateY(-50%); /*定位*/
}
- 利用table的vertical-align实现
.father {
display: table-cell; /*利用table的vertical-align实现*/
vertical-align: middle;
}
实现效果图如下: