myNewAccount
myNewAccount

Reputation: 640

When using CSS input, why might active state trigger successfully on input, but not on label? Hover state works as expected on both

Question: In the simplified example below the green hover state works as expected when the mouse is positioned over the input radio button as well as the label. However, while the yellow active state works as expected when the mouse clicks the radio button it does not fire when the mouse clicks the label. When the mouse clicks the label the radio button simply stays green. This is true in Chrome, Edge and Opera. Interestingly the only browser in which the radio buttons worked as I expected was Firefox.

    input[type="radio"] {
        -webkit-appearance: none;
        -moz-appearance: none;
        -o-appearance: none;
        appearance: none;
        width: 2rem;
        height: 2rem;
        background-color: white;
        border: .0625rem solid rgb(128, 128, 128);
        border-radius: 50%;
    }

    input[type="radio"]:checked {
        background-color: red;
    }

    input[type="radio"]:checked:hover {
        background-color: green;
    }

    input[type="radio"]:checked:active {
        background-color: yellow;
    }

    label {
        font-size: 2rem;
        user-select: none;
        color: black;
    }
    <input type="radio" name="myInput" id="first">
    <label for="first">Label 1.</label>
    <br>

    <input type="radio" name="myInput" id="second">
    <label for="second">Label 2.</label>

Upvotes: 1

Views: 167

Answers (1)

joohong89
joohong89

Reputation: 1271

A workaround solution for the other browser.

When label is placed before the radio, you can make use of the adjacent sibling selector to achieve the intended. The downside would be that additional styling is required to achieve the expected placement of radio and input.

input[type="radio"] {
        -webkit-appearance: none;
        -moz-appearance: none;
        -o-appearance: none;
        appearance: none;
        width: 2rem;
        height: 2rem;
        background-color: white;
        border: .0625rem solid rgb(128, 128, 128);
        border-radius: 50%;
    }

    input[type="radio"]:checked {
        background-color: red;
    }

    input[type="radio"]:checked:hover {
        background-color: green;
    }

    input[type="radio"]:checked:active {
        background-color: yellow;
          
    }


    
    label {
        font-size: 2rem;
        user-select: none;
        color: black;
    }
    
    label:active + input[type="radio"]:checked {
      background-color: yellow;
    } 
    
    #second {
      float: left;
    }
<input type="radio" name="myInput" id="first">
    <label for="first">Label 1.</label>
    <br>

<label for="second">Label 2.</label>
<input type="radio" name="myInput" id="second">

Upvotes: 1

Related Questions