Web - How to style a page to allow a fixed top header (Navbar / Menu) ?


If you create a region at the top of your page that is positioned fixed, it will overlay your other content:

  • when the page is loading: the top text of the page will be cached
  • when navigating with url fragment

You need to style your page further to correct this behavior.


Padding on the body

To translate the text below the fixed header towards the bottom, you need to add a padding to the body


body { padding-top: 70px; }

You can also calculate dynamically the header height and update it with Javascript.

window.requestAnimationFrame(function() {
    let fixedNavbar = document.querySelector(".navbar[data-type=\"fixed-top\"]")
    let offsetHeight = fixedNavbar.offsetHeight;

For a fixed bottom navbar, you should also correct it but with a padding-bottom

body { padding-bottom: 70px; }

When navigating / scrolling to the target element of a fragment, the default behavior is to set the target position at the top of he page. The target element are then cached by the fixed header.

To correct this behavior, you can apply the scroll-margin-top property

:target {
  scroll-margin-top: 80px;
  scroll-snap-margin-top: 80px

An old method was to create an invisible box with a negative margin but add the disadvantage to create a larger box space.

:target::before {
  content: "";
  display: block;
  margin-top: -80px;
  height: 80px;
  width: 1px;

Discover More
Bootstrap - Navbar

in Bootstrap In Bootstrap 4, the Navbar is responsive by default and utilizes flexbox to make alignment of Navbar content much easier. The navbar-header class has been removed from Bootstrap 4, and the...
Css Padding
CSS - Padding

The padding area is the space between the content of the box and its border. In the below image, this are the areas: TP (top padding) BP (bottom padding) LP (left padding) RB (right padding)...
Layout Shift Devtool Performance
Layout Shift: How to prevent it ? (Cumulative Layout Shit / CLS)

A layout shift occurs when the rendering of the web page shifts / move element from their current position. For instance: without the knowledge of the target ratio (via the height and width attribute...
URI - Fragment (Ref, Reference)

The fragment is the last part of a URI An URI has the following syntax with the #fragment being the fragment The value of the fragment must be encoded. The fragment will cause the browser to scroll...
Devtool Chrome Performance Frames
requestAnimationFrame Web Api

requestAnimationFrame is a window function that permits to run code when a frame is going to be painted. Avoiding layout shift. For instance, when you create a fixed top bar, you need to set two...

Share this page:
Follow us:
Task Runner