Sticky Site Headers and the WordPress Admin Bar
Sticky site headers are a common design pattern with our sites, and although many users will visit our site in logged-out states, it’s still worth improving the UX with just a few lines of code.
Because sticky headers are not always a feature, I’ve opted not to include it as a part of the template theme, but all the code snippets will be based on the template theme.
Code Snippets
The header.php
file should have .position-sticky
on the <header>
element.
In _header.scss
#site-header {
// ... styles
@media screen and (min-width:600.02px) {
top:var(--wp-admin--admin-bar--height,0);
}
}
- The
--wp-admin--admin-bar--height
variable is set by WordPress, so we simply use it and provide a fallback0
when the variable isn’t set. - The Media Query is because the admin bar is only using
position:fixed
at 600px and up, so it matches that—otherwise you get a random floating header (with about 46px of space above it to the top of the viewport)