Home > Net >  How to make proper toggle button for radio input
How to make proper toggle button for radio input

Time:12-22

I`m trying to make a toggle button in CSS to change theme for calculator page, but selector only working on the third theme and moving to start when I select second radio.

HTML

        <div >
          <div id="theme-name">Theme</div>
          <div >
            <div >
              <label for="first">1</label>
              <label for="second">2</label>
              <label for="third">3</label>
            </div>
            <div >
              <input type="radio" id="first" name="choice" />
              <input type="radio" id="second" name="choice" />
              <input type="radio" id="third" name="choice" />
              <span ></span>
            </div>
          </div>
        </div>
     

CSS

.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;
        }
      }

I want slider to move according to selected theme

CodePudding user response:

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;
}
  • Related