A pure CSS ON/OFF switch

A simple way to create a flip switch without any javascript, but only several lines of simple css.

The HTML consists of 3 parts:

  • the holder - it must be a <label> element;
  • <input> - it can be checkbox or radio type;
  • empty <span> - the span element must be right after the <input>.

<label class="switch">
    <input type="checkbox"><span></span>
</label>

Basicaly the idea here is to hide the <input> element and while clicking on the label you are going to "check" and "uncheck" it.

Using the ":checked" selector you'll be able to control the empty span.

Here is an example of the core idea:


<style>
.switch input{
  position: absolute;
  visibility: hidden;
}
.switch input + span{
  background:red;
}

.switch input:checked + span{
  background:blue;
}
</style>
<label class="switch">
    <input type="checkbox"><span>CLICK HERE</span>
</label>

So from here only sky is the limit. :)

You can make it look and behave the way you want.

I am going to give you an example of the popular switch control, similar to the one that is used in iOS and Android devices.

The holder('.switch') will be styled in white elliptical shape and the empty span as a circle:


.switch{
  display: inline-block;
  position: relative;
  width: 65px;
  height: 30px;
  background-color: #F7F7F7;
  border-radius: 30px;
  cursor: pointer;
}

.switch span{
  display: inline-block;
  position: absolute;
  z-index: 1;
  left: -2px;
  top: 0px;
  width: 30px;
  height: 30px;
  border: 2px solid #3472F5;
  background-color: #f9f9f9;
  border-radius: 30px;
  -webkit-transition: all 0.3s;
  -moz-transition: all 0.3s;
  -ms-transition: all 0.3s;
  -o-transition: all 0.3s;
  transition: all 0.3s;
}

And now the only thing that is missing is the 'active' state:


.switch input:checked + span{
    left:100%;
    margin-left: -30px;
    background-color: #3472F5;
}

For usability purposes you can add a "checkmark" sign for better indicating the state of the controller.


.switch:after{
  content: '\2714';
  position: absolute;
  left: 7px;
  color: #3472F5;
  top: 0;
  font-size:120%;
}

Examples


Basic Example:





Radio buttons and remote control with another label: