How to Implement a Sticky Header in Drupal with JavaScript and CSS
A sticky header stays visible while a visitor moves through long Drupal pages, keeping the primary navigation, search and contact links within easy reach. For Drupal, the most dependable pattern combines CSS position: sticky with a small JavaScript enhancement that marks the header as stuck. CSS handles the positioning; JavaScript adds a visual state, handles the administration toolbar and avoids a continuous scroll handler.
Build the feature in a custom theme or contributed theme override rather than editing Drupal core. The markup should come from a Twig template, the behaviour should run through a Drupal library and the styles should live in the theme’s CSS. This separation makes the change easier to deploy, cache and support. It also gives editors a stable header on article, landing, search and campaign pages without depending on a particular content type.
Choose the right sticky behaviour
Start by deciding what “sticky” means for the project. A persistent header remains in the normal document flow and becomes pinned to the top when its upper edge reaches the viewport. A condensed header can reduce its height after scrolling, while a hide-and-reveal header disappears in the downward direction and returns when the reader moves up. The first pattern is predictable and accessible; the others need extra rules so they do not interfere with focus, touch gestures or reduced-motion preferences.
CSS position: sticky is the core mechanism because it survives resizing and does not require recalculating element coordinates on every scroll event. Its main limitation is the layout around it: a parent with overflow: auto, overflow: hidden or a fixed height can prevent the header from staying pinned. A transform on an ancestor can also create a new containing block. Inspect the actual theme container before treating a failed sticky header as a browser defect.
Decide whether the header should be sticky on every viewport. On a small phone, the navigation may already open as a full-screen menu, so pinning a tall bar can waste scarce screen space. A media query can return it to normal flow below 48rem while retaining the desktop behaviour. For teams working across Sydney, Melbourne, Brisbane and Perth, one documented theme primitive is easier to support consistently than a collection of page-specific overrides.
Prepare the Drupal header markup
Drupal does not guarantee one universal header tag or class, so inspect the rendered HTML before changing a template. Contrib themes such as Olivero, custom themes and headless front ends can all structure the page differently. Locate the element containing the page_header region, then wrap that content in a semantic <header> or add the hook to the existing one. Do not duplicate the navigation, because repeated links and duplicate IDs can make keyboard and screen-reader navigation confusing.
Add a tiny sentinel immediately before the header and a data attribute on the header itself. The sentinel is the point the observer watches; it does not need meaningful content and remains hidden from assistive technology. In a page template, the relevant portion can resemble the following:
{{ page_top }}
<div class="sticky-header-sentinel"
data-sticky-header-sentinel
aria-hidden="true"></div>
<header class="site-header" data-drupal-sticky-header>
{{ page_header }}
</header>
If the theme cannot expose a template override, Drupal’s preprocessing layer can still add the attribute to the relevant wrapper, although a template is usually clearer. Load the custom JavaScript and CSS as one theme library, then attach that library from the theme’s info.yml. The once helper prevents the behaviour from binding twice when Drupal renders regions through AJAX or BigPipe.
sticky-header:
version: 1.0
css:
theme:
css/sticky-header.css: {}
js:
js/sticky-header.js: {}
dependencies:
- core/drupal
- core/once
For useful diagnostics while the feature is live, use a Drupal logging guide to capture related server-side errors without logging personal data. The browser console remains the right place for JavaScript exceptions and failed asset requests.
Style the sticky state with CSS
The baseline CSS should work even if JavaScript is unavailable. Position the real header, assign a high stacking order and make its background opaque so page content cannot show through. Keep the offset in a custom property because Drupal’s administration toolbar may occupy space above it for logged-in editors.
:root {
--sticky-header-offset: 0px;
--sticky-header-height: 5rem;
}
.site-header {
position: sticky;
top: var(--sticky-header-offset);
z-index: 1000;
background-color: var(--site-header-background, #fff);
}
.sticky-header-sentinel {
height: 1px;
margin-bottom: -1px;
pointer-events: none;
}
.site-header.is-stuck {
box-shadow: 0 0.25rem 1rem rgb(0 0 0 / 14%);
}
:target {
scroll-margin-top: calc(var(--sticky-header-height) + 1rem);
}
@media (prefers-reduced-motion: no-preference) {
.site-header {
transition: box-shadow 160ms ease;
}
}
The is-stuck class is applied by JavaScript when the sentinel has moved above the viewport. It can add a shadow, border or stronger background without changing the header’s geometry. The transition is limited to a visual property and is disabled when reduced motion is requested. The measured height is exposed as another custom property, allowing anchored sections to use scroll-margin-top and stay clear of the pinned header.
Watch the wrappers around the header. Sticky positioning fails when an ancestor clips or scrolls its content, and a fixed-height page container can limit the travel distance. Avoid using overflow: hidden as a quick fix on the body; correct the component’s containing block instead. Keep theme labels and comments in Australian English, such as “colour” and “prioritise”, and verify the final background against both the light and dark colour schemes used by the site.
Add a JavaScript state enhancer
Use a Drupal JavaScript behaviour so the feature starts with the component and survives partial page updates. IntersectionObserver watches the sentinel and calls the class change only when the crossing occurs. This is cheaper and smoother than running geometry calculations in a frequent scroll listener. The implementation below also measures the administration toolbar and header, keeping the sticky header below Drupal’s toolbar and keeping anchor offsets accurate.
Place the following in the theme’s JavaScript file:
(function (Drupal, once) {
'use strict';
Drupal.behaviors.stickyHeader = {
attach: function (context) {
once(
'sticky-header',
'[data-drupal-sticky-header]',
context
).forEach(function (header) {
var sentinel = header.previousElementSibling;
if (
!sentinel ||
!sentinel.hasAttribute('data-sticky-header-sentinel')
) {
sentinel = document.createElement('div');
sentinel.className = 'sticky-header-sentinel';
sentinel.setAttribute('data-sticky-header-sentinel', '');
sentinel.setAttribute('aria-hidden', 'true');
header.parentNode.insertBefore(sentinel, header);
}
function updateMeasurements() {
var toolbar = document.querySelector('#toolbar-administration');
var offset = 0;
if (
toolbar &&
window.getComputedStyle(toolbar).position === 'fixed'
) {
offset = toolbar.getBoundingClientRect().height;
}
document.documentElement.style.setProperty(
'--sticky-header-offset',
offset + 'px'
);
document.documentElement.style.setProperty(
'--sticky-header-height',
header.offsetHeight + 'px'
);
}
var observer = new IntersectionObserver(function (entries) {
var entry = entries[0];
var isStuck =
!entry.isIntersecting && entry.boundingClientRect.top <= 0;
header.classList.toggle('is-stuck', isStuck);
}, { threshold: 0 });
observer.observe(sentinel);
updateMeasurements();
if ('ResizeObserver' in window) {
var resizeObserver = new ResizeObserver(updateMeasurements);
resizeObserver.observe(header);
} else {
window.addEventListener('resize', updateMeasurements, {
passive: true
});
}
});
}
};
})(Drupal, once);
The observer deliberately changes only a class; the CSS continues to own positioning and appearance. That separation prevents the common problem where a fixed header suddenly removes itself from the document flow and causes a jump. If a browser in the support matrix lacks IntersectionObserver, add a small polyfill or a passive, throttled scroll fallback. If a hosted staging environment delivers assets inconsistently, investigate the platform path with VMkernel network troubleshooting before altering the theme code.
Test and maintain the implementation
Test the result with a keyboard, a touch screen and browser zoom at 200%, then repeat at common Drupal breakpoints. Include pages with long titles, utility navigation, an open mobile menu and the administration toolbar. Check that the skip link remains the first focus target, that focus outlines are visible and that dropdown menus can close before the header moves. A quick “have a squiz” at the header in different browsers is cheaper than discovering a collision after deployment.
Performance matters outside metropolitan areas as well as in city offices. Test cached and uncached pages over 4G and 5G, because a header should not make meaningful content wait for a large JavaScript bundle. Keep the behaviour small, defer non-essential header scripts and avoid loading a separate animation library for one shadow. Australian Drupal agencies frequently maintain sites for universities, councils and not-for-profits, so document the behaviour in the theme README and include it in the support runbook.
During maintenance, compare the rendered header with the design system and test after a Drupal core, contrib module or library update. Sticky behaviour can be affected by a changed toolbar, a new wrapper or altered region markup. Use version-controlled CSS and JavaScript, keep the sentinel selector narrow and review the custom properties in browser developer tools. For public-sector work, check the implementation against WCAG 2.2 AA and the Australian Government Digital Service Standard rather than relying on visual inspection alone.
| Approach | How it works | Best suited to | Main limitation |
|---|---|---|---|
| CSS-only sticky | Uses position: sticky without JavaScript |
Simple headers with reliable parent containers | Limited state styling and ancestor overflow restrictions |
| CSS and JavaScript | Sticky CSS with an observed state class | Drupal themes needing shadows, toolbar offsets or diagnostics | Requires a maintained theme library and frontend testing |
| JavaScript fixed header | Changes position during scrolling and reserves space | Hide-and-reveal designs or legacy sticky constraints | More complex resizing and greater layout-shift risk |
| Design-system component | Uses an established header primitive | Teams with a shared component library | May limit control over Drupal-specific markup and behaviour |