Today I have found an interesting code snippet with changing layout of radio buttons using only css. Snippet is available on codepen.

All code and view is available on the codepen. However I put a code snippets here in case someone remove it from codepen.

<div class="container">
  <div class="radio">
    <input id="radio-1" name="radio" type="radio" checked>
    <label for="radio-1" class="radio-label">Checked</label>
  </div>

  <div class="radio">
    <input id="radio-2" name="radio" type="radio">
    <label  for="radio-2" class="radio-label">Unchecked</label>
  </div>

  <div class="radio">
    <input id="radio-3" name="radio" type="radio" disabled>
    <label for="radio-3" class="radio-label">Disabled</label>
  </div>
</div>
$color1: #f4f4f4;
$color2: #3197EE;

body {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
}

.radio {
  margin: 0.5rem;
  input[type="radio"] {
    opacity: 0;
    position: absolute;
    + .radio-label {
      &:before {
        content: '';
        background: $color1;
        border-radius: 100%;
        border: 1px solid darken($color1, 25%);
        display: inline-block;
        width: 1.4em;
        height: 1.4em;
        margin-right: 1em; 
        vertical-align: top;
        cursor: pointer;
        text-align: center;
        transition: all 250ms ease;
      }
    }
    &:checked {
      + .radio-label {
        &:before {
          background-color: $color2;
          box-shadow: inset 0 0 0 4px $color1;
        }
      }
    }
    &:focus {
      + .radio-label {
        &:before {
          outline: none;
          border-color: $color2;
        }
      }
    }
    &:disabled {
      + .radio-label {
        &:before {
          box-shadow: inset 0 0 0 4px $color1;
          border-color: darken($color1, 25%);
          background: darken($color1, 25%);
        }
      }
    }
    + .radio-label {
      &:empty {
        &:before {
          margin-right: 0;
        }
      }
    }
  }
}

Hope you will enjoy that solution.

Styling radio buttons with css
Tagged on:                     

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Social Widgets powered by AB-WebLog.com.