CSS scroll snap and smooth scrolling in a WordPress theme
A horizontal row of cards that stops neatly at each card, anchor links that glide to their section and do not end up under the sticky header: these used to be jobs for a carousel script. Today CSS does them with scroll-snap-type, scroll-behavior and scroll-margin-top, with native touch scrolling on phones.
Problem: A theme uses a jQuery carousel for a row of post cards, and the table of contents jumps to headings that end up hidden under the sticky header.
Solution: Make the card row a horizontal scroll container with scroll-snap-type: x mandatory and scroll-snap-align on the cards, add previous/next buttons with scrollBy(), set scroll-behavior: smooth only for visitors who did not ask for reduced motion, and give the headings a scroll-margin-top.
A card row that snaps
.ha-cards {
display: flex;
gap: 1.5rem;
overflow-x: auto;
scroll-snap-type: x mandatory;
overscroll-behavior-x: contain;
padding-bottom: 0.75rem; /* room for the scrollbar */
}
.ha-cards > .ha-card {
flex: 0 0 min(80vw, 320px);
scroll-snap-align: start;
}
mandatory always stops at a card; proximity stops only when the scroll ends near one, which is better for long items. overscroll-behavior-x: contain keeps a swipe at the end of the row from triggering the browser’s back gesture.
Keep the scrollbar visible: it shows that the row scrolls, and mouse users without a trackpad need it.
Previous and next buttons
<div class="ha-cards-nav">
<button type="button" data-dir="-1" aria-label="Previous posts">←</button>
<button type="button" data-dir="1" aria-label="Next posts">→</button>
</div>
document.querySelectorAll( '.ha-cards-nav' ).forEach( ( nav ) => {
const row = nav.nextElementSibling; // the .ha-cards element
nav.addEventListener( 'click', ( event ) => {
const button = event.target.closest( 'button[data-dir]' );
if ( button && row ) {
row.scrollBy( { left: Number( button.dataset.dir ) * row.clientWidth * 0.8, behavior: 'smooth' } );
}
} );
} );
After scrollBy() the browser still snaps to the nearest card, so the step does not have to match the card width exactly.
Smooth anchors under a sticky header
@media (prefers-reduced-motion: no-preference) {
html {
scroll-behavior: smooth;
}
}
:where(h2, h3, [id]) {
scroll-margin-top: calc(var(--ha-header-height, 80px) + 1rem);
}
.admin-bar :where(h2, h3, [id]) {
scroll-margin-top: calc(var(--ha-header-height, 80px) + 32px + 1rem);
}
scroll-margin-top moves the stop point of the anchor jump down by the height of the sticky header, for links in the same page and for links from other pages. Logged-in users have the admin bar (32 px, 46 px on small screens) on top as well. The sticky header itself: position: sticky explained.
NOTE: Avoid full-screen sections with scroll-snap-type: y mandatory on the whole page: content taller than the screen becomes hard to read, keyboard scrolling jumps, and visitors feel the page fights them. Snap horizontal rows and leave the vertical page scroll alone.