posts - post layout - v2

All-CSS Toggle Switch

Comments

On a project I'm currently working on, I wanted to have a checkbox that looked like a toggle, but wanted to keep it simple — class="toggle".

<input type="checkbox" class="toggle" />

I started with the shape/container of the toggle button.

Toggle Example

.toggle {
    height: 25px;
    width: 45px;
    border-radius: 16px;
    display: inline-block;
    position: relative;
    margin: 0;
    border: 1px solid #c4cbcd;
    background: #fff;
    transition: all 0.2s ease;
}

Next, I added the button in the "unchecked" state.

Toggle Example

toggle {
    ...

    &:after {
        content: "";
        position: absolute;
        top: 2px;
        left: 2px;
        width: 19px;
        height: 19px;
        border: 1px solid #c4cbcd;
        border-radius: 50%;
        background: #fff;
        box-shadow: 0 1px 2px rgba(44, 44, 44, 0.2);
        transition: all 0.2s ease-out;
    }
}

After that, we need to add the "checked" state. This can be as complicated or as simple as you want it to be. For me, I just wanted to change the background and border colors.

Toggle Example

toggle {
    ...

    &:checked {
        background: #19c1ff;
        border-color: #19c1ff;
    }

     &:checked:after {
        border: 1px solid #fff;
        background: #fff;
        transform: translatex(20px);
    }
}

Now, if you wanted to get a little fancier, you could add an icon to the button. This could be done many different ways, but for this example I'll use Font Awesome. We just need to add a :before selector for both the unchecked and checked states.

Toggle Example

toggle {
    ...

    &:before {
        font-family: "Font Awesome";
        font-weight: 400;
        content: "";
        color: #19c1ff;
        z-index: 1;
        line-height: 19px;
        font-size: 11px;
        width: 19px;
        height: 19px;
        top: 2px;
        text-align: center;
        position: absolute;
        opacity: 0;
        transition: all 0.2s ease-out, opacity 0.2s ease-in;
    }

     &:checked:before {
        content: "\f00c";
        transform: translatex(22px);
        opacity: 1;
    }
}

🎉 We're done! Now you can just add the toggle class to any checkbox and instant toggle!