Toggle radio input using CSS only

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

    I have a solution which is halfway through:

    • It clears selection on double click but not on click (as requested)
    • But (and that's the "halfway"), it will not clear selection when double clicking the currently selected item (only when double clicking other items)

     .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%;
            }
    
            .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;
                width: 200px;
                height: 200px;
                z-index: 1;
                display: none;
            }
    
            .container #img1:checked ~ label[for=none],
            .container #img2:checked ~ label[for=none],
            .container #img3:checked ~ label[for=none] {
                display: block;
            }
    
            @keyframes hideNone {
                from {
                    z-index: 3;
                }
                to {
                    z-index: 3;
                }
            }
    
            .container #img1:checked ~ label[for=img1],
            .container #img2:checked ~ label[for=img2],
            .container #img3:checked ~ label[for=img3] {
                animation-name: hideNone;
                animation-delay: 0.3s;
                animation-duration: 99999s;
            }
    
            .container #img1:checked ~ label[for=none] {
                left: 0;
            }
    
            .container #img2:checked ~ label[for=none] {
                left: 220px;
            }
    
            .container #img3:checked ~ label[for=none] {
                left: 440px;
            }
    
            .container #img1:checked ~ #img1txt,
            .container #img2:checked ~ #img2txt,
            .container #img3:checked ~ #img3txt {
                display: block
            }
    Recipe nr 1
    Recipe nr 2
    Recipe nr 3

    Still thinking on how to improve it... :)

提交回复
热议问题