Using best practices to create CSS scroll snapping tabs
Using best practices to create CSS scroll snapping tabs
By Brecht De Ruyte
4 min read
How should scroll snapping tabs behave when using keys? By reading some best practices, I believe I found an elegant solution.
- Authors
- Name
- Brecht De Ruyte
- linkedinBrecht De Ruyte
- twitter@utilitybend
- Website
- websiteBlog
Scroll snapping is hip and while we all have styled numerous sorts of tab panes and scroll boxes, I had an idea of combining them. What started out as a simple “scroll snapping experiment” turned out to be an accessibility study.
The basic scroll snapping idea with CSS.
It started out as a simple test. By having a container with 2 lists. The lists would be next to each other and by scrolling left and right, you could toggle between them.
The HTML setup was very simple:
<section class="scroll-snap-panel">
<div class="scroll-container container">
<ul class="scroll-list people">
<!-- some list items here -->
</ul>
<ul class="scroll-list groups">
<!-- some list items here -->
</ul>
</div>
</section>
The .scroll-container
would become a grid with 2 items that have the full width of their container. The scroll container would have an overflow-x
and some smooth scroll snapping options.
Here is the basic CSS for this:
:root {
--container-width: 480px;
}
.container {
display: grid;
}
.scroll-snap-panel {
width: 100%;
margin: 30px auto;
box-shadow: rgba(0, 0, 0, 0.3) 0px 10px 50px;
max-width: var(--container-width);
}
/* the scroll magic */
.scroll-container {
position: relative;
grid-template-columns: repeat(2, var(--container-width));
-webkit-overflow-scrolling: touch;
overflow-x: scroll;
scroll-snap-type: x mandatory;
scroll-behavior: smooth;
max-height: 85vh;
border: 1px solid #ccc;
border-top: 0;
}
.scroll-list {
display: block;
width: 100%;
height: 80vh;
margin: 0;
padding: 0;
list-style: none;
scroll-snap-align: start;
scroll-snap-type: y proximity;
overflow-y: scroll;
}
.scroll-list li {
display: grid;
grid-template-columns: 80px 1fr;
gap: 20px;
align-items: center;
padding: 15px 20px;
border-bottom: 1px solid #aaa;
scroll-snap-align: start;
}
(codepen for the first step here)
A fun little component, but not accessible at all.
There are a two main problems with this little component:
- It can only be navigated by using a mouse / trackpad
- There is no indication that it can be scrolled horizontally if you don’t have your scrollbars visible at all times.
In short, not accessible at all and it got me thinking. What if I made a hybrid component where you can use this awesome scroll snapping functionality in combination with tabs. This would:
- Create a fun mobile experience
- Still have the functionality of tabs
- Would fix some accessibility issues along the way
First things first, fixing the UX.
(Visual representation of this step)
The first thing on the agenda was making an indication of the hidden content simply by adding some tabs to our HTML:
<section class="scroll-snap-panel">
<div class="tabs-container container">
<button data-target="people-tab" class="people tab active">People</button>
<button data-target="groups-tab" class="groups tab">Groups</button>
</div>
<div class="scroll-container container">
<ul class="scroll-list people" id="people-tab">
<!-- List items here -->
</ul>
<ul class="scroll-list groups" id="groups-tab">
<!-- List items here -->
</ul>
</div>
</section>
The next thing I did was adding a bit of CSS for the active tabs and adding some JS, which will use the tabs to scroll to the right position. You can view the CSS in the demo, but the basic idea of the JS was the following:
const tabs = document.querySelectorAll('.tab')
const scrollContainer = document.querySelector('.scroll-container')
const scrollLists = document.querySelectorAll('.scroll-list')
/* check for clicks and update scroll position based on target offset */
tabs.forEach((tab) => {
tab.addEventListener('click', () => {
const target = document.getElementById(tab.dataset.target).offsetLeft
scrollContainer.scrollLeft = target
})
})
/*
when the scrollcontainer is scrolled horizontally,
check the current scrollposition is the same as the left offset,
and set the tab active when that's the case
*/
scrollContainer.addEventListener('scroll', () => {
let scrollPos = scrollContainer.scrollLeft
scrollLists.forEach((list) => {
let listId = list.id
let listButton = document.querySelector(`.tab[data-target="${listId}"]`)
if (scrollPos === list.offsetLeft) {
;[...listButton.parentElement.children].forEach((sib) => {
sib.classList.remove('active')
})
listButton.classList.add('active')
}
})
})
And for a moment, I thought it was perfect:
- It has an indication of multiple panes
- You can use tab and shift-tab to switch between tabs and enter to activate them.
But I still wasn’t happy. There was no indication of tabs when using voice over, The list is not vertically scrollable with a keyboard. So when it came to accessibility. I still had ways to go.
The final improvement to make it accessible.
(Visual representation of this step)
I knew I had some reading to do. So I started looking at the documentation of tabs at the aria working group website. A quick summary of how tabs should behave:
Using TAB
- The first TAB should enter the tab component on the first (active) button.
- The second TAB should change the focus inside the active tabpanel.
- The third TAB should leave the tabbed component
Arrow keys
- While focussing on the tab button, the arrows should switch between them.
- The tabpanels can either be activated automatically while using the arrow or manually by pressing the enter key (for this example, I chose automatically)
Special case
Because I'm working with scroll behaviour, I wanted the arrow keys to work inside the tabpanel itself. By pressing the left or right arrow key while scrolling through the list, I want it to switch the active panel and focus on the new active tab as an indication of what happened.
They have some great examples at the ARIA working group, so based on their example of automated tabs, I started by changing my HTML to the following:
<section class="scroll-snap-panel" role="tablist" aria-label="users and groups">
<div class="tabs-container container">
<button
data-target="people-tab"
role="tab"
aria-selected="true"
class="people tab active"
aria-controls="people-tab"
>
People
</button>
<button
data-target="groups-tab"
role="tab"
aria-selected="false"
class="groups tab"
aria-controls="groups-tab"
tabindex="-1"
>
Groups
</button>
</div>
<div class="scroll-container container">
<div
class="scroll-list people"
role="tabpanel"
tabindex="0"
id="people-tab"
aria-label="people"
>
<ul>
<!-- list items here -->
</ul>
</div>
<div
class="scroll-list groups"
role="tabpanel"
tabindex="-1"
id="groups-tab"
aria-label="groups"
hidden="hidden"
>
<ul>
<!-- list items here -->
</ul>
</div>
</div>
</section>
Something to note here. You might notice that I wrapped my lists inside another <div>
. This is because a role=”tabpanel”
should not be used on an unordered list.
By adding a bit of JS from the ARIA working group and infusing it with my own code. I was able to create something interesting and accessible. I learned a lot from this experience and the goal of this post was to take you on a little thought journey. Accessibility is very important, and we might not get it perfect all the time, but a bit of effort can go a long way.
The final example, with kudos to people who create examples in the ARIA working group.
Upcoming events
Drupal CMS Launch Party
Zoals sommigen misschien weten wordt op 15 Januari een nieuwe distributie van Drupal gelanceerd. Namelijk Drupal CMS (ook wel bekend als Starshot). Om dit te vieren gaan we op onze campus een klein eventje organiseren. We gaan die dag samen de livestream volgen waarbij het product gelanceerd wordt. De agenda is als volgt: 17u – 18u30: Drupal CMS livestream met taart 18u30 – 19u00: Versteld staan van de functionaliteiten 19u – 20u: Pizza eten en verder versteld staan van de functionaliteiten Laat ons zeker weten of je komt of niet door de invite te accepteren! Tot dan!
| Coven of Wisdom Herentals
Go to page for Drupal CMS Launch PartyCoven of Wisdom - Herentals - Winter `24 edition
Worstelen jij en je team met het bouwen van schaalbare digitale ecosystemen of zit je vast in een props hell met React of in een ander framework? Kom naar onze meetup waar ervaren sprekers hun inzichten en ervaringen delen over het bouwen van robuuste en flexibele applicaties. Schrijf je in voor een avond vol kennis, heerlijk eten en een mix van creativiteit en technologie! 🚀 18:00 – 🚪 Deuren open 18:15 – 🍕 Food & drinks 19:00 – 📢 Building a Mature Digital Ecosystem - Maarten Heip 20:00 – 🍹 Kleine pauze 20:15 – 📢 Compound Components: A Better Way to Build React Components - Sead Memic 21:00 – 🙋♀️ Drinks 22:00 – 🍻 Tot de volgende keer? Tijdens deze meetup gaan we dieper in op het bouwen van digitale ecosystemen en het creëren van herbruikbare React componenten. Maarten deelt zijn expertise over het ontwikkelen van een volwassen digitale infrastructuur, terwijl Sead je laat zien hoe je 'From Props Hell to Component Heaven' kunt gaan door het gebruik van Compound Components. Ze delen praktische inzichten die je direct kunt toepassen in je eigen projecten. 📍 Waar? Je vindt ons bij iO Herentals - Zavelheide 15, Herentals. Volg bij aankomst de borden 'meetup' vanaf de receptie. 🎫 Schrijf je in! De plaatsen zijn beperkt, dus RSVP is noodzakelijk. Dit helpt ons ook om de juiste hoeveelheid eten en drinken te voorzien - we willen natuurlijk niet dat iemand met een lege maag naar huis gaat! 😋 Over iO Wij zijn iO: een groeiend team van experts die end-to-end-diensten aanbieden voor communicatie en digitale transformatie. We denken groot en werken lokaal. Aan strategie, creatie, content, marketing en technologie. In nauwe samenwerking met onze klanten om hun merken te versterken, hun digitale systemen te verbeteren en hun toekomstbestendige groei veilig te stellen. We helpen klanten niet alleen hun zakelijke doelen te bereiken. Samen verkennen en benutten we de eindeloze mogelijkheden die markten in constante verandering bieden. De springplank voor die visie is talent. Onze campus is onze broedplaats voor innovatie, die een omgeving creëert die talent de ruimte en stimulans geeft die het nodig heeft om te ontkiemen, te ontwikkelen en te floreren. Want werken aan de infinite opportunities van morgen, dat doen we vandaag.
| Coven of Wisdom Herentals
Go to page for Coven of Wisdom - Herentals - Winter `24 editionThe Test Automation Meetup
PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Test automation is a cornerstone of effective software development. It's about creating robust, predictable test suites that enhance quality and reliability. By diving into automation, you're architecting systems that ensure consistency and catch issues early. This expertise not only improves the development process but also broadens your skillset, making you a more versatile team member. Whether you're a developer looking to enhance your testing skills or a QA professional aiming to dive deeper into automation, RSVP for an evening of learning, delicious food, and the fusion of coding and quality assurance! 🚀🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 First round of Talks 19:45 – 🍹 Small break 20:00 – 📢 Second round of Talks 20:45 – 🍻 Drinks 21:00 – 🙋♀️ See you next time? First Round of Talks: The Power of Cross-browser Component Testing - Clarke Verdel, SR. Front-end Developer at iO How can you use Component Testing to ensure consistency cross-browser? Overcoming challenges in Visual Regression Testing - Sander van Surksum, Pagespeed | Web Performance Consultant and Sannie Kwakman, Freelance Full-stack Developer How can you overcome the challenges when setting up Visual Regression Testing? Second Round of Talks: Omg who wrote this **** code!? - Erwin Heitzman, SR. Test Automation Engineer at Rabobank How can tests help you and your team? Beyond the Unit Test - Christian Würthner, SR. Android Developer at iO How can you do advanced automated testing for, for instance, biometrics? RSVP now to secure your spot, and let's explore the fascinating world of test automation together!
| Coven of Wisdom - Amsterdam
Go to page for The Test Automation Meetup