Search code examples
bootstrap-4flexboxvertical-alignment

Just cannot get flex to vertically center an element with bootstrap or vanilla flexbox


i am losing my marbles here. i have been through the top posts that i can find on stackoverflow that match my issue, flexbox's own resources, and bootstrap's tuts, and i have tried to implement these myself. Either there is a fundamental CSS value that i am still missing (certainly possible) or a fundamental flexbox value that i am still missing or something i am completely misunderstanding. I am using Bootstrap 4 and have never managed to vertically center an element using flex.

My Markup content with Bootstrap classes included appears just below. The H1 element is being centered successfully along the x-axis, but not the y-axis.

<section>
    <div class="container">
        <div class="row">
            <div class="col-12">
                <div class="d-flex align-items-center justify-content-center">
                    <h1 class="neoretrodraw logo text-center">Logo Text Here</h1>
                </div>
            </div>
        </div>
    <div>
</section>

Please, PLEASE, do not simply point at another post or posts on this same website - i am acutely aware that this question may have been answered in a different form before and have done my reading. I feel like this is a simple thing i am missing out on with a simple mistake.


Solution

  • You just need to use class vh-100 in your flex class as well for x and y-axix centring the h1

    Live Demo:

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <section>
      <div class="container">
        <div class="row">
          <div class="col-12">
            <div class="vh-100 d-flex align-items-center justify-content-center">
              <h1 class="neoretrodraw logo text-center">Logo Text Here</h1>
            </div>
          </div>
        </div>
      </div>
    </section>