在网页开发中,我们经常需要让内容垂直居中显示,而且CSS中也提供了几种方法实现这个效果。下面我们来一一介绍。/ 方法一:使用lineheight属性 / .parent{ height: 200px;...
在网页开发中,我们经常需要让内容垂直居中显示,而且CSS中也提供了几种方法实现这个效果。下面我们来一一介绍。
/* 方法一:使用line-height属性 */
.parent{
height: 200px; /* 父容器高度 */
line-height: 200px; /* 行高等于父容器高度 */
}
.child{
vertical-align: middle;
}
/* 方法二:使用flex布局 */
.parent{
height: 200px; /* 父容器高度 */
display: flex; /* flex布局 */
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
}
/* 方法三:使用table-cell属性 */
.parent{
height: 200px; /* 父容器高度 */
display: table; /* 元素表格化 */
}
.child{
display: table-cell; /* 子元素表格单元格 */
vertical-align: middle; /* 垂直居中 */
} 以上三种方法都可以很好地实现垂直居中效果,不过要根据实际情况选择合适的方法,同时也要注意浏览器的兼容性问题。