Home >Web Front-end >CSS Tutorial >How to Vertically Center a Container in Bootstrap: Flexbox vs. Pseudo-Element?

How to Vertically Center a Container in Bootstrap: Flexbox vs. Pseudo-Element?

Susan Sarandon
Susan SarandonOriginal
2024-12-18 18:27:18543browse

How to Vertically Center a Container in Bootstrap: Flexbox vs. Pseudo-Element?

How to Vertically Center a Container in Bootstrap

Using Flexible Box Layout (Modern Method)

For modern browsers, you can vertically center a container using the flexbox layout:

<div class="jumbotron vertical-center">
  <div class="container">
    ...
  </div>
</div>
.vertical-center {
  min-height: 100vh;
  display: flex;
  align-items: center;
}

Using ::before Pseudo-Element (Legacy Method)

For older browsers, you can use a ::before pseudo-element to create a full-height element that will align the container vertically:

<div class="jumbotron vertical-center">
  <div class="container">
    ...
  </div>
</div>
.vertical-center {
  height: 100%;
  width: 100%;
  text-align: center;
  font: 0/0 a;
}

.vertical-center:before {
  content: " ";
  display: inline-block;
  vertical-align: middle;
  height: 100%;
}

.vertical-center > .container {
  max-width: 100%;
  display: inline-block;
  vertical-align: middle;
  font: 16px/1 "Helvetica Neue", Helvetica, Arial, sans-serif;
}

Additional Considerations

  • To prevent unexpected issues on small screens, you can reset the height of the ::before pseudo-element to auto or 0.
  • If there are footer/header sections around the container, position them properly and add a higher z-index value to keep them on top.

The above is the detailed content of How to Vertically Center a Container in Bootstrap: Flexbox vs. Pseudo-Element?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn