DEV Community

loading...

The simplest CSS toggle in 3 steps.

leonardoschmittk profile image Leonardo Schmitt Updated on ・2 min read

Here I will show a simple way to make a toggle using only HTML5 and CSS3 files. It's beginner friendly, so there are a bunch of explanations. Chances are if you just see the code snippets you will understand. Let's go...

1. Add the HTML

<div class="toggle">
   <div class="toggle__cell"></div>
</div> 
Enter fullscreen mode Exit fullscreen mode

2. Add the toggle event

To do so we are using an inline script right away in the toggle__cell element.

<div class="toggle">
   <div class="toggle__cell" onclick='this.classList.toggle("toggle--active")'></div>
</div> 
Enter fullscreen mode Exit fullscreen mode

The this refers to the toggle__cell and whenever occur a click on it, a specific class to differ the non-toggled and toggled is added. Now let's jump into the CSS.

3. Windup with the CSS

Actually it is already working, the element now 'know' when it's toggled. Though, there's no visual signal for it, and with CSS we are making it done.

First, the style of toggle is the following

 .toggle {
            width: 50px;
            height: 23px;
            display: flex;
            align-items: center;
            background: #ffffff;
            box-shadow: inset 0 0 10px #e4e4e4;
            border-radius: 20px;
         }
Enter fullscreen mode Exit fullscreen mode

We are putting the toggle__cell in the center using flex-box and adding a slight effect of shadow.

.toggle__cell {
            width: 15px;
            height: 15px;
            cursor: pointer;
            background: radial-gradient(#2d8ef5 30%, #a889fff1);
            border-radius: 50%;
            transition: transform ease-in-out 0.4s;
            transform: translateX(5px);
         }
Enter fullscreen mode Exit fullscreen mode

Here we just make the cell combine with its father, a slight gradient, circle form and an initial placement with translateX to not touch the border-left of the father, but it could be made by tons of others approaches, such as padding or left positioning. Moreover there's the transition to turn the toggle sorta "pleasant", as well as adding the mouse cursor as it was a button.

Finally we make the visual difference between non-toggled and toggled:

.toggle--active {
            transform: translateX(30px);
         }
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

pic
Editor guide
Collapse
arthurassuncao profile image
Arthur Nascimento Assunção

Good. The code isn't pure html and css because onclick property executes a js code,
Tip for next articles: include preview or live preview and, if possible, complete code in codepen with live run and preview.