htmlcsstoggleswitch

How to display cross mark in the toggle switch when disabled


I am using a toggle switch and I want to show a tick mark when enabled and an x-mark when disabled.

and am able to show the tick mark but unable to display the x-mark. please help me where I am doing wrong.

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked+.slider {
  background-color: #2196F3;
}

input:focus+.slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked+.slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}


/* Rounded sliders */

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}

.toggle-switch-container {
  display: flex;
  align-items: center;
}


/* Style the toggle switch label */

.toggle-switch-label {
  margin-left: 10px;
  font-size: 20px;
}


/* Tick and Cross marks */

.tick,
.cross {
  position: absolute;
  top: 2px;
  font-size: 22px;
  color: white;
  transition: .4s;
}

.tick {
  left: 35px;
  opacity: 0;
}

input:checked+.slider+.tick {
  opacity: 1;
  color: green;
}

.cross {
  right: 34px;
  opacity: 0;
}

input:not(:checked)+.slider+.cross {
  color: red;
  opacity: 1;
}
<div class="toggle-switch-container">
  <label class="switch">
            <input type="checkbox" checked>
            <span class="slider round"></span>
            <span class="tick">&#10003;</span>
            <span class="cross">&#10005;</span>
        </label>
</div>

when enable tick mark showing properly like this

enter image description here

and when disabled i want x-mark(crosser) like tick mark

enter image description here

thanks


Solution

  • It is because you are using the adjacent sibling selector + to select .cross but unlike .tick it is not the adjacent sibling to .slider. Try using general sibling selector ~ like this:

    input:not(:checked) ~ .cross {
      color: red;
      opacity: 1;
    }