在CSS中,我们经常需要将元素垂直居中,下面我们将介绍一种常用方法,在div中垂直居中元素。
<div class="container">
<div class="content">
内容
</div>
</div>
.container {
height: 100px;
display: flex;
justify-content: center;
align-items: center;
}
.content {
height: 50px;
width: 100px;
background-color: #ccc;
} 以上代码中,我们使用了Flex布局,将.container中的元素垂直居中。
首先,指定.container的高度为100px,即我们的容器高度为100px。
然后,使用Flex布局,justify-content: center表示水平居中,align-items: center表示垂直居中。
最后,给.content指定高度和宽度,并设置背景色,即我们要垂直居中的元素。
使用以上代码,我们就可以将元素在div内垂直居中了。