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

Time:10-25

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/[email protected]/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/[email protected]/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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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/[email protected]/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/[email protected]/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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related