How to add a persistent navigation bar to a theme

My question is possibly very basic, but I am trying to add a persistent navigation bar at the top, as in this site. So, just to explain this, in this site itself, at the top, we have a persistent bar in black (which I call persistent) because as I scroll down, that bar continues to stay at the top, allowing for easier navigation for the reader – s/he does not have to scroll back to the top in order to get to another link/section. How do I do this/where?

Many thanks in advance for answering this potentially basic question.

Google “css sticky nav bar” or similar. That’s a CSS question, not a Hugo question.

Just to expand on what was said above. In Hugo, your navigation lives in a partial (usually header.html or nav.html). The key is making sure it’s in your baseof.html layout outside the main content block, so it persists across all pages:

{{ partial "nav.html" . }}
<main>
  {{ block "main" . }}{{ end }}
</main>

For the sticky behaviour, add this CSS to your nav element:

nav {
  position: sticky;
  top: 0;
  z-index: 100;
}

position: sticky is well supported now and doesn’t need any JavaScript. It stays in the document flow until you scroll past it, then sticks to the top. Much cleaner than position: fixed which takes the element out of flow and can cause layout shifts.

2 Likes