DEV Community

Utsav Mavani
Utsav Mavani

Posted on

Create a square radio button

To create a square radio button with a value inside, you can use HTML and CSS. Here's an example of how you can achieve this:

<!DOCTYPE html>
<html>
<head>
  <style>
    /* Style for the radio button container */
    .radio-container {
      display: inline-block;
      position: relative;
      padding-left: 30px; /* Adjust the size of the square */
    }

    /* Style for the radio button input */
    .radio-container input[type="radio"] {
      position: absolute;
      opacity: 0;
      cursor: pointer;
    }

    /* Style for the radio button label (the square) */
    .radio-container .radio-square {
      position: absolute;
      top: 0;
      left: 0;
      width: 20px; /* Adjust the size of the square */
      height: 20px; /* Adjust the size of the square */
      background-color: #3498db; /* Color of the square */
      border: 1px solid #3498db; /* Border around the square */
    }

    /* Style for the value inside the square */
    .radio-container .radio-value {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      color: white; /* Color of the text */
    }

    /* Style for the radio button label when selected */
    .radio-container input[type="radio"]:checked + .radio-square {
      background-color: #e74c3c; /* Change the color when selected */
    }
  </style>
</head>
<body>
  <label class="radio-container">
    <input type="radio" name="myRadioButton" value="A">
    <span class="radio-square">
      <span class="radio-value">A</span>
    </span>
  </label>

  <label class="radio-container">
    <input type="radio" name="myRadioButton" value="B">
    <span class="radio-square">
      <span class="radio-value">B</span>
    </span>
  </label>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

In this example, we create a custom radio button using a label element that wraps an input of type "radio." We style the radio button using CSS. You can adjust the size of the square and its color as needed. The value inside the square is specified within the radio-value class. The example shows two radio buttons with values "A" and "B," but you can add more as needed.

Top comments (0)