在本教程中,我们将通过实例来学习如何在Bootstrap中水平和垂直地将一个div居中。
考虑一下,在Bootstrap中我们有如下的div元素。
<div>
<h1>Hello, User</h1>
</div>
class 要在Bootstrap中使一个div水平和垂直居中,请在div元素的d-flex 和justify-content-center,align-items-center 属性中添加utlity类。
"justify-content-center "使div水平居中。
"align-items-center "使div垂直居中。
下面是一个例子。
<div class="d-flex justify-content-center align-items-center" style="100vh">
<h1>Hello, User</h1>
</div>
注意:上述实用类使用的是flexbox,可以在Bootstrap 4和5版本上工作。
如果你使用的是低于4的Bootstrap版本,那么你可以使用自定义CSS类来添加flexbox。
<div class="center">
<h1>Hello, User</h1>
</div>
.center{
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
使用绝对位置在水平和垂直方向上将div居中
我们可以使用bootstrap中的css绝对定位来使一个div水平和垂直居中。
下面是一个例子。
<div class="center">
<h1>Hello, User</h1>
</div>
.center{
position:absolute;
left:50%;
top:50%;
transform:translate(-50%, -50%);
}
-
这里我们给div元素添加了
position:absolute,因此该元素脱离了正常的文档流程,被定位到其相对的父元素(例如:body或父元素)。 -
left:50%将该元素从其位置向右移动50%。 -
top:50%将该元素从其位置上向下移动50%。 -
translate(-50%, -50%)将元素向上移动50%,向左移动50%的位置。