Center element vertically on site with a Navbar on the site in bootstrap 4

Viewed 26

I try to center an element centered vertically on the page. That works fine. But if I add a Navbar, the element is centered verically but with a offset from the height of the Navbar. How can I center the content container vertically inclusive the Navbar height?

body,html {
  height: 100%;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>

<nav class="navbar navbar-light bg-light">
  <span class="navbar-brand h1">Navbar</span>
</nav>

<div class="container d-flex h-100">
    <div class="row align-self-center w-100">
        <div class="col-6 mx-auto">
            <div class="jumbotron">
                <h1 class="display-4 text-truncate">Jumbotron</h1>
                <p class="lead">This is a simple hero unit.</p>
                <p class="lead">
                    <a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a>
                </p>
            </div>
        </div>
    </div>
</div>

1 Answers

You can put the navbar fixed on top by adding fixed-top class to it.

body,html {
  height: 100%;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>

<nav class="navbar navbar-light bg-light fixed-top">
  <span class="navbar-brand h1">Navbar</span>
</nav>

<div class="container d-flex h-100">
    <div class="row align-self-center w-100">
        <div class="col-6 mx-auto">
            <div class="jumbotron">
                <h1 class="display-4 text-truncate">Jumbotron</h1>
                <p class="lead">This is a simple hero unit.</p>
                <p class="lead">
                    <a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a>
                </p>
            </div>
        </div>
    </div>
</div>

Related