Explain Codes LogoExplain Codes Logo

Twitter bootstrap navbar fixed top overlapping site

html
responsive-design
css
javascript
Alex KataevbyAlex Kataev·Dec 19, 2024
TLDR

Get rid of overlapping content with a fixed-top Bootstrap navbar by adding padding-top to your <body> tag. The padding should equal the navbar's height. For a navbar standing at the typical height of 50px, use:

body { padding-top: 70px; } /* Watch the magic as your content is pushed down by 70px ;) */

In the case of Bootstrap 4+, apply the spaciously helpful spacing utility classes:

<body class="pt-5"> /* No navbar shall dare obscure my content! */ </body>

This neatly ensures your content starts below the navbar, preventing the indignity of overlapping upon scrolling.

Taking padding-top to the tailor

If your layout features unique elements or an unusually bulky navbar, customize the padding. Measure the actual height if it's more than the default 50px and change the padding-top accordingly.

body { padding-top: 95px; } /* Our navbar ate too many pixels and grew a bit */

Embracing responsive design

Media queries to the rescue for keeping padding-top in line with different screen sizes. Bootstrap's navbar could wrap items as the screen shrinks, requiring different strategies:

@media (min-width: 768px) { body { padding-top: 70px; } /* Desktop-size screens deserve desktop-size padding */ } @media (max-width: 767.98px) { body { padding-top: 50px; } /* Smaller screens, smaller problems, smaller padding */ }

Swap "navbar-fixed-top" with "sticky-top" for a non-obstructive content flow:

<nav class="navbar navbar-default sticky-top"> /* I'm sticking around, but I won't stand in your way */ </nav>

To become a sticky-top expert, refer to the Bootstrap 4 documentation.

Got multiple elements trying to steal the limelight with overlays? Gain control using the z-index:

.navbar-fixed-top { z-index: 1030; } /* Higher than the default, because my navbar deserves the best view */

Dynamic navigation elements

Styling for dynamic elements, such as an expandable search bar, can vary your navbar height. Use a JavaScript function to keep up:

function fixNavbarOverlap() { const navbarHeight = document.querySelector('.navbar').offsetHeight; document.body.style.paddingTop = `${navbarHeight}px`; } // Rerun when the window resizes, because a changing view deserves a rerun! window.addEventListener('resize', fixNavbarOverlap); fixNavbarOverlap();

Shifting content quick-fix

A layout shift might occur when adding padding-top. Using the .navbar.navbar-default.navbar-static-top class provides a shift-resistant layout.

Fixed vs sticky navbar: The ultimate showdown

Choosing between fixed-top and sticky-top truly depends on what experience you offer. Remember, fixed-top flaunts the navbar always, while sticky-top elegantly limelights the navbar only after a scrolling threshold.