BootStrap - 将一个div元素水平居中的方法

4,243 阅读1分钟

在本教程中,我们将通过实例来学习如何在BootStrap中把一个div元素水平居中。

考虑一下,我们在BootStrap中有如下的div元素。

<div>
  <h1>Hello, User</h1>
</div>

class 要在BootStrap中使一个div水平居中,请在div元素的d-flexjustify-content-center 属性中添加utlity类。

"justify-content-center "使DIV水平居中。

下面是一个例子。

<div class="d-flex justify-content-center">
  <h1>Hello, User</h1>
</div>

注意:上述实用类使用的是flexbox,可以在BootStrap 4,和5版本上工作。

如果你使用的是低于4的Bootstrap版本,那么你可以使用自定义CSS类来添加flexbox。

<div class="center-h">
  <h1>Hello, User</h1>
</div>
.center-h{
    display: flex;
    justify-content: center;
}

使用绝对位置将div水平居中

我们可以使用bootstrap中的CSS绝对定位来使一个div水平居中。

下面是一个例子。

<div class="center-h">
     <h1>Hello, User</h1>
</div>
.center-h{
   position: absolute;
   left: 50%;
   transform: translateX(-50%);
}
  1. 这里我们给div元素添加了position:absolute ,所以该元素脱离了正常的文档流程,被定位到其相对的父元素(例如:body或父元素)。

  2. left:50% 将该元素从其位置向右移动50%。

  3. translateX(-50%) 将元素从它的位置向左移动50%。