How to create custom tabs component using only HTML and CSS (no-js)

kyoshee
2 min readJun 5, 2022

Originally posted on kyoshee.com

Today we will talk about the tabs component. This is one of the popular ways to present information, which allows you to group content and place relevant information in the same place on the screen.

tl;dr

The result is a simple tabs component that works without JavaScript: full markup with styles in a CodePen.

Photo by Panos Sakalakis on Unsplash

Markup preparation

The tabs will always be placed above the content and act as navigation, so we wrap them in a header block and a nav navigation block. The place for the content will be allocated with the section element, and the content of each tab will be located inside the article.

Initial markup

Binding elements

To bind the links and their respective tabs, we'll use the href attributes on the anchors and the id attributes on the article by assigning them the appropriate values. So, by clicking on each anchor, the browser will send us to the corresponding tag with the identifier specified in the href.

Markup with id and href attributes

Styles

Let's start styling the components. At first, we need to hide all elements with the tag-article class, and arrange the tabs in a convenient order. In my case, I used flexbox for tabs. Don't forget to add padding to the tabs to make them easier to hit. We will also add styles to the :hover and :focus elements for the a elements for accessibility, so that the user can distinguish when he hovered over the area of ​​our “button” or highlighted it with the focus using the tab.

Styles for tabs wrapper and section with content
Styles for tabs

To make sure that when a link (anchor) is clicked, the corresponding content appears on the page, we add a :target pseudo-element to the article, which will select the article with the corresponding id, which the link leads to and which appears in the address bar. It is worth noting here that if you want the section to not be empty at the beginning, pass in the URL the id of the article that you want to see when the page loads, for example https://my.site/tabs#tab1.

Styles for selected article

Let’s add a small animation of the appearance of the content and disable it if the user wants to see less animation in their browser using the prefers-reduced-motion: reduce media query.

Animation styles

Result

The result is a simple tabs component that works without JavaScript: full markup with styles on a CodePen.

Thanks for reading!

--

--