在本教程中,我们将学习如何使用CSS将div元素中的文本垂直居中。
考虑一下,我们在div的HTML里有以下文字。
<div class="container">
<h1>Welcome to the blog</h1>
</div>
要使文本在div内垂直居中,可将display:flex 和align-items: center 添加到div 的CSS类中。
"align-items: center "将文本垂直居中。
下面是一个例子。
<div class="container">
<h1>Welcome to the blog</h1>
</div>
CSS。
.container{
display: flex;
align-items: center;
height: 100%;
}
或者我们可以使用HTML中的style 属性为div元素添加内联样式。
<div style="display: flex;justify-content: center; height: 100%;" >
<h1>Welcome to the blog</h1>
</div>
在div中使用绝对位置将文本垂直居中
我们可以使用css中的绝对定位来使文本在div元素中垂直居中。
下面是一个例子。
<div class="container">
<h1>Welcome to the blog</h1>
</div>
.container{
position:absolute;
top:50%;
transform:translateY(-50%);
}
-
在上面的例子中,我们给div元素添加了
position:absolute,因此该元素脱离了正常的文档流程,并定位到其相对父元素(例如:body或父元素)。 -
top:50%将该元素从其位置向下移动50%。 -
translateY(-50%)将元素从它的位置向上移动50%。