Working with Fixed Headers in CSS
Lots of websites use fixed headers as part of their design, but there are often unintended consequences to implementing such a design element.
I recently chose to implement a fixed header (specifically, a navigation pane) on this website. I use <nav>
tags to wrap the navigation elements, as per the HTML specification. Here, I will describe the practical steps to fix my navigation header and make it work across my website.
As a background, pages on my website are generally structured as follows:
<html>
<body>
<div class="skiptocontent>
<!-- Accessibility -->
<a href="#content">Skip to content</a>
</div>
<nav>
<!-- Navigation elements -->
</nav>
<header>
<!-- Header elements for sub-sites -->
</header>
<main>
<article>
<!-- Main content -->
</article>
</main>
<footer>
<!-- Footer content -->
</footer>
</body>
</html>
It’s important to note that not all pages have <header>
tags; just my blogs and sub-sites, such as the Story of Flowers.
Fixing the Navigation Header
To fix the navigation header, the CSS is relatively simple, relying on the position:fixed
element and targeting the <nav>
elements:
nav {
position: fixed;
top: 0;
left: 0;
width: 100%;
flex: 1;
padding: 0em;
flex-flow: row;
display: flex;
height: 3em;
border-bottom: rgb(84, 115, 241) solid 1px;
backdrop-filter: blur(10px);
z-index: 100;
}
Whilst this will create a fixed header, it can create other problems.
Adjusting Banner Headers
The problem with fixing a header is that other elements in the website may then become obscured, such as the <header>
elements that sit below.
In the example above, the navigation header has a height of 3em, which means that the banner header that sits below it will be partially hidden. To fix this, add the following to your CSS file:
header {
margin-top: 3em;
}
Here, you can see the difference illustrated:
Bookmarks and Anchors
Bookmarks (also called anchors) can also present a problem when combined with a fixed header. This is because the default behavior for browsers is to scroll an anchor to the top of a view port, which means it will also be obscured.
The solution to this problem is surprisingly simple:
html {
scroll-padding-top: 5.5em;
}
This piece of CSS overrides the browser’s behaviour by leaving a space above the bookmark when the page is scrolled to it.
Remember to leave a space greater than the thickness of the fixed header. In my case, the fixed <nav>
element is 3em, so I have set this to 5.5em.
Comments
No comments have yet been submitted. Be the first!