DEV Community

loading...

Creating tabs with CSS only

cadienvan profile image Michael Di Prisco ・2 min read

[TL;DR] Here's the demo: Codepen

If you haven't already...

Take a look at my first post to proper understand the premise of the series: Creating a lateral menu with CSS only

Let's go...

As I did in my last article, I limited the amount of work on UI and UX for the sake of simplicity, to provide a simple and usable solution that could be easily explained and understood.

The HTML...

There you have it, simple and clean:

<!DOCTYPE html>
<html>
  <body>
    <!-- Our First Tab Trigger -->
    <label for="firstTab">Toggle First Tab</label>
    <!-- Our Second Tab Trigger -->
    <label for="secondTab">Toggle Second Tab</label>


    <!-- Our First Checkbox -->
    <input type="radio" class="radio-tab-toggle" name="tabTest" id="firstTab" value="1" />
    <!-- Our First Tabbed Content -->
    <div>First Tab</div>

    <!-- Our Second Checkbox -->
    <input type="radio" class="radio-tab-toggle" name="tabTest" id="secondTab" value="2" />  </body>
    <!-- Our First Tabbed Content -->
    <div>Second Tab</div>
</html>
Enter fullscreen mode Exit fullscreen mode

The CSS...

CSS is probably the shortest and simplest I ever written, 3 rules and we have our tabs:

.radio-tab-toggle{
  margin: -1px;
  padding: 0;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip: rect(0 0 0 0);
  clip: rect(0, 0, 0, 0);
  position: absolute;
}

.radio-tab-toggle + div {
  height: 0;
  overflow: hidden;
}

.radio-tab-toggle:checked + div {
  height: auto;
}

Enter fullscreen mode Exit fullscreen mode

So there we have it.. By clicking on the trigger labels, we check our invisible checkboxes and, consequently, make our content visible.

Level it up a bit..

The only issue I can see here is the lack of "close current tab" functionality. In fact, as far as I know, you can't "uncheck" a radio box group once you checked one of its components. So I guess we could level it up a bit via a simple JS snippet.

The JS...

Third post, third time you ask for it. How do I have to tell you?

JS = false;
Enter fullscreen mode Exit fullscreen mode

Conclusion...

Nice experiment, but limited to the lack of possibility to uncheck a checked radio-box without JS.

Give me a heart, a unicorn, or whatever you want! See you soon!

Discussion (0)

pic
Editor guide