Toggle radio input using CSS only

前端 未结 6 1737
慢半拍i
慢半拍i 2020-12-09 04:00

The following code use a script to toggle/uncheck a radio when clicked a second time on the same.

My question is how do I do this using CSS only?

6条回答
  •  无人及你
    2020-12-09 04:40

    You can't change the functionality of radio buttons using CSS. CSS is designed for visual changes only.

    That said, you can simulate this behavior with a clever hack. For your example, I'd recommend using CSS to visually replace the label for the currently selected radio button with a dummy label attached to another radio button representing a "blank" or "empty" selection. That way, clicking the dummy label would select the "blank" option, effectively clearing your prior choice:

    .container {
      display: flex;
      flex-wrap: wrap;
      max-width: 660px;
    }
    .container > label {
      flex: 1;
      flex-basis: 33.333%;
    }
    .container > div {
      flex: 1;
      flex-basis: 100%;
    }
    .container label img {
      display: block;
      margin: 0 auto;
    }
    .container input, .container input ~ div {
      display: none;
      padding: 10px;
    }
    
    .container #img1:checked ~ #img1txt,
    .container #img2:checked ~ #img2txt,
    .container #img3:checked ~ #img3txt {
      display: block;
    }
    
    .container label[for=noimg] {
      display: none;
    }
    
    .container #img1:checked ~ label[for=img1],
    .container #img2:checked ~ label[for=img2],
    .container #img3:checked ~ label[for=img3] {
      display: none;
    }
    
    .container #img1:checked ~ label[for=img1] + label[for=noimg],
    .container #img2:checked ~ label[for=img2] + label[for=noimg],
    .container #img3:checked ~ label[for=img3] + label[for=noimg] {
      display: block;
    }
    Recipe nr 1
    Recipe nr 2
    Recipe nr 3

    (View in JSFiddle)

提交回复
热议问题