Search code examples
cssradio-buttoncentering

How to properly center checked radio button?


I was styling a radio button and couldn't center the dot when checked. I tried using absolute positioning and grid display to center it, but I was unsuccessful. Can somebody tell me the reason and how to solve it?

/*--------styling using absolute poistionning---------*/
input[type="radio"]#id2{
    appearance: none;
    position: relative;
    border-radius: 50%;
    height: 1.6rem;
    width: 1.6rem;
    cursor: pointer;
    border:2px solid rgb(18, 141, 223);
}

input[type="radio"]#id2::after{
    position: absolute;
    transform: translate(0.1rem,0.1rem);
    content:"";
    opacity: 0;
    border-radius: 50%;
    height: 1.2rem;
    width: 1.2rem;
    font-size: 1.2rem;
    line-height: 2rem;
    cursor: pointer;
    background: rgb(18, 141, 223);
}

input[type="radio"]#id2:checked::after{
    opacity: 1;
    transition: ease 450ms;
}

/*-----------------styling using grid----------*/

input[type="radio"]#id1 {
    appearance: none;
    display: grid;
    place-items: center;
    border-radius: 50%;
    height: 1.6rem;
    width: 1.6rem;
    cursor: pointer;
    border:2px solid rgb(18, 141, 223);
}

input[type="radio"]#id1::after{
    content:"";
    opacity: 0;
    border-radius: 50%;
    height: 1.2rem;
    width: 1.2rem;
    cursor: pointer;
    background: rgb(18, 141, 223);
}

input[type="radio"]#id1:checked::after{
    opacity: 1;
    transition: ease 450ms;
}
<label for="id1">using grid layout</label><br>
<input type="radio" name="transport" id="id1">
<label for="id2">using absolute positionning</label><br>
<input type="radio" name="transport" id="id2">

I have tried both ways without success.


Solution

  • Use an easier way

    input[type="radio"] {
      appearance: none;
      border-radius: 50%;
      height: 1.6rem;  /* size */
      aspect-ratio: 1;
      padding: .1rem;  /* gap */
      color: rgb(18, 141, 223); /* color */
      border: 2px solid;
      transition: .2s;
    }
    input[type="radio"]:checked {
      background: currentColor content-box;
    }
    <input type="radio" name="transport">
    <input type="radio" name="transport">