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
Release: 2024-12-18 18:27:18
Original
494 people have browsed it

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>
Copy after login
Copy after login
.vertical-center {
  min-height: 100vh;
  display: flex;
  align-items: center;
}
Copy after login

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>
Copy after login
Copy after login
.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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template