Search code examples
cssformsradio-buttonchecked

CSS - Custom styling on radio button


I have a jsfiddle here - https://jsfiddle.net/5qmnptuk/4/

I'm trying to craete a custom radio button.

Ive hidden the radio button and then created the new one with :after on the label.

I'm trying to use :checked to style the clicked but its not working

Can anyone see why this doesn't work.

    .form-group{
        margin-top: 30px;
    }

    label{
        cursor: pointer;
        display: inline-block;
        position: relative;
        padding-right: 25px;
        margin-right: 15px;
    }

    label:after{
        bottom: -1px;
        border: 1px solid #aaa;
        border-radius: 25px;
        content: "";
        display: inline-block;
        height: 25px;
        margin-right: 25px;
        position: absolute;
        right: -31px;
        width: 25px;
    }

    input[type=radio]{
        display: none;
    }

    input[type=radio]:checked + label{
        content: \2022;
        color: red;
        font-size: 30px;
        text-align: center;
        line-height: 18px; 
    }

Solution

  • There are several problems with your code:

    1 - Your input needs to be before the label

    The + and ~ CSS selectors only select siblings after an element in the DOM, so you need to have the input before the label.

    2 - Your label isn't assigned to the input

    To assign the label, use the for attribute, and give the input an ID:

      <div class="form-group">
        <input type="radio" id="custom" />
        <label for="custom">Label</label>
      </div>
    

    3 - The content for the pseudo element is missing quotes.

    4 - You aren't applying the styles to the after element of the label, you were applying them to the label directly:

     input[type=radio]:checked + label{
        content: \2022;
        color: red;
        font-size: 30px;
        text-align: center;
        line-height: 18px; 
    }
    

    Selects the label, while:

    input[type=radio]:checked + label:after{
        content: "\2022";
        color: red;
        font-size: 30px;
        text-align: center;
        line-height: 18px; 
    }
    

    Selects the after element

    Updated, working JSFiddle