Toggle radio input using CSS only

前端 未结 6 1736
慢半拍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:36

    Bounty Challenge Accepted (without the extra noimg)

    .container {
        display: flex;
        flex-wrap: wrap;
        max-width: 660px;
        overflow: hidden;
        position: relative;
    }
    .container img {
        user-select: none;
        pointer-events: none;
    }
    .container > label {
        flex: 1;
        flex-basis: 33.333%;
        z-index: 1;
    }
    .container > div {
        flex: 1;
        flex-basis: 100%;
    }
    .container label img { margin: 0 auto }
    .container input,
    .container input ~ div {
        display: none;
        padding: 10px;
    }
    .container label[for=none] {
        position: absolute;
        bottom: 0;
        top: 0;
        left: 0;
        right: 0;
        z-index: 0;
    }
    .container #img1:checked ~ label[for=img1],
    .container #img2:checked ~ label[for=img2],
    .container #img3:checked ~ label[for=img3] {
        pointer-events: none;
        z-index: -1;
    }
    .container #img1:checked ~ #img1txt,
    .container #img2:checked ~ #img2txt,
    .container #img3:checked ~ #img3txt { display: block }
    Recipe nr 1
    Recipe nr 2
    Recipe nr 3


    EDIT: By definition radio buttons shouldn't be toggleable (I forgot that this was an additional requirement in this task = to broke the rules). @Ajedi32 answer is probably the best, but it can be optimized (repeated images)? Bounty still in game...

    EDIT 2: Now it's fully functional solution. (doing this trick https://stackoverflow.com/a/7392038/2601031)

    EDIT 3: Multi-layer layout + Repaired selection.

提交回复
热议问题