Reputation: 13
I`m trying to make a toggle button in CSS to change the theme for a calculator page, but the selector only works on the third theme and moving to start when I select the second radio.
.form-choice {
#first:checked + .slider:before {
transform: translateX(0px);
background-color: red;
}
#second:checked + .slider:before {
transform: translateX(15px);
background-color: black;
}
#third:checked + .slider:before {
transform: translateX(45px);
background-color: yellow;
}
}
<div class="theme-selector">
<div id="theme-name">Theme</div>
<div class="theme-form">
<div class="form-name">
<label for="first">1</label>
<label for="second">2</label>
<label for="third">3</label>
</div>
<div class="form-choice">
<input type="radio" id="first" name="choice" />
<input type="radio" id="second" name="choice" />
<input type="radio" id="third" name="choice" />
<span class="slider"></span>
</div>
</div>
</div>
I want the slider to move according to selected the theme.
Upvotes: 1
Views: 57
Reputation: 1501
You’re using the wrong selector in your CSS.
The +
selector is called an “adjacent sibling” selector. It will select only the second element so long as it immediately follows the first.
The ~
is a “general sibling” selector and doesn’t have the same condition of having to immediately follow the first element.
Try:
#first:checked ~ .slider:before {
transform: translateX(0px);
background-color: red;
}
#second:checked ~ .slider:before {
transform: translateX(15px);
background-color: black;
}
#third:checked ~ .slider:before {
transform: translateX(45px);
background-color: yellow;
}
Upvotes: 2