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
The 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? 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 MeetupCoven of Wisdom - Herentals - Winter `24 edition
Worstelen jij en je team met automated testing en performance? Kom naar onze meetup waar ervaren sprekers hun inzichten en ervaringen delen over het bouwen van robuuste en efficiënte 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 – 📢 Talk 1 20:00 – 🍹 Kleine pauze 20:15 – 📢 Talk 2 21:00 – 🙋♀️ Drinks 22:00 – 🍻 Tot de volgende keer? Tijdens deze meetup gaan we dieper in op automated testing en performance. Onze sprekers delen heel wat praktische inzichten en ervaringen. Ze vertellen je hoe je effectieve geautomatiseerde tests kunt schrijven en onderhouden, en hoe je de prestaties van je applicatie kunt optimaliseren. Houd onze updates in de gaten voor meer informatie over de sprekers en hun specifieke onderwerpen. 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 editionMastering Event-Driven Design
PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Are you and your team struggling with event-driven microservices? Join us for a meetup with Mehmet Akif Tütüncü, a senior software engineer, who has given multiple great talks so far and Allard Buijze founder of CTO and founder of AxonIQ, who built the fundaments of the Axon Framework. RSVP for an evening of learning, delicious food, and the fusion of creativity and tech! 🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 Getting Your Axe On Event Sourcing with Axon Framework 20:00 – 🍹 Small break 20:15 – 📢 Event-Driven Microservices - Beyond the Fairy Tale 21:00 – 🙋♀️ drinks 22:00 – 🍻 See you next time? Details: Getting Your Axe On - Event Sourcing with Axon Framework In this presentation, we will explore the basics of event-driven architecture using Axon Framework. We'll start by explaining key concepts such as Event Sourcing and Command Query Responsibility Segregation (CQRS), and how they can improve the scalability and maintainability of modern applications. You will learn what Axon Framework is, how it simplifies implementing these patterns, and see hands-on examples of setting up a project with Axon Framework and Spring Boot. Whether you are new to these concepts or looking to understand them more, this session will provide practical insights and tools to help you build resilient and efficient applications. Event-Driven Microservices - Beyond the Fairy Tale Our applications need to be faster, better, bigger, smarter, and more enjoyable to meet our demanding end-users needs. In recent years, the way we build, run, and operate our software has changed significantly. We use scalable platforms to deploy and manage our applications. Instead of big monolithic deployment applications, we now deploy small, functionally consistent components as microservices. Problem. Solved. Right? Unfortunately, for most of us, microservices, and especially their event-driven variants, do not deliver on the beautiful, fairy-tale-like promises that surround them.In this session, Allard will share a different take on microservices. We will see that not much has changed in how we build software, which is why so many “microservices projects” fail nowadays. What lessons can we learn from concepts like DDD, CQRS, and Event Sourcing to help manage the complexity of our systems? He will also show how message-driven communication allows us to focus on finding the boundaries of functionally cohesive components, which we can evolve into microservices should the need arise.
| Coven of Wisdom - Utrecht
Go to page for Mastering Event-Driven Design