📜  center div bootstrap 4 (1)

📅  最后修改于: 2023-12-03 15:29:57.319000             🧑  作者: Mango

Centering a div in Bootstrap 4

In web development, centering an element is a common task that can sometimes be tricky to accomplish. However, with Bootstrap 4, it is easy to center a div horizontally or vertically.

Horizontally Centering a div

To horizontally center a div, you can simply apply the class mx-auto to the div. This class sets the left and right margins to auto, which centers the div horizontally. Here is an example:

<div class="container">
  <div class="row">
    <div class="col-md-6 mx-auto">
      <p>This div is centered horizontally.</p>
    </div>
  </div>
</div>

In the example above, the mx-auto class is applied to a col-md-6 div. This centers the div horizontally within its parent container.

Vertically Centering a div

To vertically center a div, you can use the Flexbox utilities in Bootstrap 4. The approach involves using a combination of the d-flex, align-items-center, and justify-content-center classes. Here is an example:

<div class="container h-100">
  <div class="row h-100 justify-content-center align-items-center">
    <div class="col-md-6">
      <p>This div is centered vertically.</p>
    </div>
  </div>
</div>

In the example above, the parent container has a height of h-100 to fill the entire height of the viewport. The row div has the justify-content-center and align-items-center classes applied to it. This centers the child div vertically and horizontally within the row.

Conclusion

Centering a div can be a common task in web development, but with Bootstrap 4, it is made simple using the mx-auto and Flexbox utilities. Use these approaches to easily center your divs in Bootstrap 4.