How to build a scroll-to-top button in Drupal with CSS
Long Drupal landing pages are common in Australian publishing, retail and membership projects. A catalogue page built for a Sydney fashion seller or a Melbourne event venue can contain hundreds of products, speakers or search results, so returning to the page header becomes a practical navigation task. A scroll-to-top button gives visitors a predictable way to recover that position without repeatedly swiping or reaching for the keyboard.
The useful pattern is a small team of parts: accessible Twig markup, a fixed CSS component and a lightweight behaviour that reveals it after the page has moved. CSS owns placement, colour, focus styling and motion; JavaScript only manages visibility and the threshold. This keeps the control independent of contributed modules and makes it practical for custom themes maintained by Drupal agencies across the Australian market.
Performance matters beyond the major cities. A visitor opening a long article on a phone in Perth or on a regional connection in Brisbane should not download an icon font, tracking script or broad animation package to move up one page. An inline SVG, a few CSS rules and one passive scroll listener avoid that overhead, while a plain anchor still works if scripting is unavailable.
Privacy and accessibility are equally relevant for Australian sites. The control needs no cookie, identifier or analytics event, which helps teams working under the Australian Privacy Act 1988 and Privacy Principles keep the feature deliberately narrow. Keyboard users also need a visible focus state, and people who request reduced motion should receive an immediate jump rather than a long animated transition.
Choose the right implementation
Start with behaviour rather than appearance. Decide how far a visitor must scroll before the control appears, where it should sit, and whether it remains available on short pages. A threshold around 400 pixels works for many editorial and catalogue templates: the button is out of the way initially, but it becomes available before a visitor reaches an awkward point near the footer.
The three practical options differ in how they move the page, when they appear and what happens when JavaScript is unavailable:
| Approach | Scroll movement | Appears after scrolling | JavaScript-free fallback | Typical use |
|---|---|---|---|---|
| Plain anchor and CSS | Smooth when allowed | No; always visible | Yes | Small sites and fixed links |
| CSS plus a small Drupal behaviour | Smooth with a visibility threshold | Yes | Yes | Most Drupal themes |
| Third-party interface library | Often smooth | Usually yes | Depends | Interfaces needing many widgets |
The CSS-and-script approach is the best balance for most Drupal themes. CSS alone can style and position an anchor, but it cannot reliably know when the page has crossed a scroll threshold; a dedicated library adds weight for a feature this small. The hybrid keeps a usable link without JavaScript, adds a refined reveal when scripting is active and avoids changes to Drupal core.
Add accessible markup with Twig
Put the destination and control in the custom theme rather than editing a core template. The body can provide a stable top target, while the link can live near the end of page.html.twig; because it is fixed with CSS, its source position does not create space in the document flow. Add the data-scroll-to-top hook so JavaScript can find it without relying on a brittle class name.
Preserve the markup already provided by the custom theme and make the body focusable programmatically:
{# html.html.twig #}
<!DOCTYPE html>
<html{{ html_attributes }}>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
{{ head }}
{{ stylesheets }}
{{ scripts }}
</head>
<body{{ attributes.addClass('site-body').setAttribute('id', 'top').setAttribute('tabindex', '-1') }}>
{{ page_top }}
{{ page }}
{{ page_bottom }}
</body>
</html>
In page.html.twig, render the control after the main page content:
<a class="scroll-to-top"
href="#top"
data-scroll-to-top
aria-label="Back to top">
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path d="M12 19V5M5 12l7-7 7 7" />
</svg>
</a>
The aria-label names the icon-only control for screen readers, and aria-hidden prevents the decorative SVG from being announced separately. If the same control must appear in several regions, the patterns in advanced Twig templating can keep the markup consistent without duplicating it by hand. A custom module is another reasonable home when non-technical editors must toggle the feature; in that case, expose the threshold and visibility as configuration instead of hard-coding them in a template.
Style the fixed control with CSS
The component should be independent of any particular layout width. A fluid right offset keeps the control aligned with a constrained content area on a wide Sydney office display, while the minimum gap keeps it clear of the edge on a narrow phone. The bottom offset also accounts for the iPhone home indicator, a useful detail on Australian sites where many visitors browse on iOS devices.
:root {
--scroll-to-top-size: 3rem;
--scroll-to-top-gap: 1rem;
}
html.has-scroll-to-top-js {
scroll-behavior: smooth;
}
.scroll-to-top {
position: fixed;
right: max(var(--scroll-to-top-gap), calc(50vw - 40rem));
bottom: calc(var(--scroll-to-top-gap) + env(safe-area-inset-bottom, 0px));
display: inline-flex;
align-items: center;
justify-content: center;
width: var(--scroll-to-top-size);
height: var(--scroll-to-top-size);
border: 2px solid transparent;
border-radius: 999px;
background: #0b5cab;
color: #fff;
text-decoration: none;
box-shadow: 0 4px 16px rgb(0 0 0 / 25%);
z-index: 1000;
transition: opacity 180ms ease, transform 180ms ease;
}
.has-scroll-to-top-js .scroll-to-top:not(.is-visible) {
opacity: 0;
visibility: hidden;
pointer-events: none;
transform: translateY(0.75rem);
}
.scroll-to-top.is-visible {
opacity: 1;
visibility: visible;
transform: translateY(0);
}
.scroll-to-top:hover {
background: #084a91;
}
.scroll-to-top:focus-visible {
outline: 3px solid #f59e0b;
outline-offset: 3px;
}
.scroll-to-top svg {
width: 1.25rem;
height: 1.25rem;
fill: none;
stroke: currentColor;
stroke-width: 2;
stroke-linecap: round;
stroke-linejoin: round;
}
@media (prefers-reduced-motion: reduce) {
html.has-scroll-to-top-js {
scroll-behavior: auto;
}
.scroll-to-top {
transition: none;
}
}
CSS custom properties make safe adjustments straightforward. Change the size, gap or colours in one place, and check the result against the theme’s button tokens rather than hard-coding a second palette. For related layout decisions, the spacing ideas in responsive Flexbox techniques can be adapted when the control shares a footer with other floating tools.
The hidden state uses visibility as well as opacity. That removes the control from the accessibility tree and prevents pointer interaction, whereas opacity alone can leave an invisible link in the tab order. A :focus-visible outline must contrast with the page, and the reduced-motion block should disable both smooth scrolling and the reveal transition.
Control visibility with lightweight JavaScript
Keep the JavaScript in a theme library so Drupal can cache and aggregate it with the rest of the theme assets. The CSS is attached to the same library, and the theme information file loads that library on every page where the component appears. The script uses a Drupal behaviour so initialisation stays aligned with the DOM and the code has a clear home in version control.
Assuming the custom theme’s machine name is drupalwoo, create these files inside the theme. Register the assets in drupalwoo.libraries.yml, then merge the library into the existing libraries list in drupalwoo.info.yml so the component loads globally.
# drupalwoo.libraries.yml
scroll_to_top:
version: 1.0.0
dependencies:
- core/drupal
css:
theme:
css/scroll-to-top.css: {}
js:
js/scroll-to-top.js:
scope: header
# drupalwoo.info.yml
libraries:
- drupalwoo/scroll_to_top
The implementation below adds the enhancement class only when a matching control exists. A requestAnimationFrame guard limits visual updates during fast scrolling, and the passive scroll listener does not delay the browser’s handling of touch input. The click handler leaves the anchor’s native URL-fragment behaviour intact; it only moves keyboard focus to the top target before the browser completes the jump.
(function (Drupal) {
'use strict';
Drupal.behaviors.scrollToTop = {
attach: function (context) {
const buttons = Array.from(
context.querySelectorAll('[data-scroll-to-top]')
);
if (!buttons.length) {
return;
}
document.documentElement.classList.add('has-scroll-to-top-js');
const threshold = 400;
let framePending = false;
const update = () => {
const visible = window.scrollY > threshold;
buttons.forEach((button) => {
button.classList.toggle('is-visible', visible);
});
};
const requestUpdate = () => {
if (framePending) {
return;
}
framePending = true;
window.requestAnimationFrame(() => {
update();
framePending = false;
});
};
window.addEventListener('scroll', requestUpdate, { passive: true });
window.addEventListener('resize', requestUpdate, { passive: true });
update();
buttons.forEach((button) => {
button.addEventListener('click', () => {
const target = document.getElementById('top');
if (target) {
target.focus({ preventScroll: true });
}
});
});
},
};
}(Drupal));
If the visitor lands partway down the page, the first update immediately calculates whether the button should appear. CSS supplies the smooth movement, while the reduced-motion media query overrides it for people who ask their operating system to limit animation. If JavaScript fails, the link remains visible and still returns to #top through an ordinary anchor navigation.
Test the finished feature in real conditions
Test the finished feature at real content lengths. Open a node with a long body, a search-results view, a webform confirmation and a commerce listing in Drupal. Check the button at the threshold, at the footer and after returning upward. On mobile, verify that it does not cover form errors, cookie controls, chat widgets or the bottom navigation used by the site.
Accessibility testing should include keyboard-only use, VoiceOver on iOS and NVDA on Windows, plus automated checks in tools such as Accessibility Insights. The control should be reachable by Tab and activate with Enter. Its accessible name should describe the destination, its colour contrast should meet WCAG 2.2 AA and its focus indicator must remain visible against both the button and the page behind it.
Before deployment, clear Drupal’s CSS and JavaScript caches, then confirm that aggregation has not changed the selector names or reordered the script. Place the change in the custom theme’s Git branch and promote it through the same staging workflow used for other Australian agency projects. The feature sends no personal data and introduces no external request, making its operational footprint easy to document.
Once deployed, the button should fade in only after meaningful scrolling, remain clear of regional layouts and return both the viewport and keyboard focus to the document start. Its small footprint and theme-level ownership make it straightforward to maintain when content, branding or Drupal upgrades change.