Sobes.tech
Junior

How do you style checkboxes and other input elements such as inputs?

sobes.tech AI

Answer from AI

Styling checkboxes and radio buttons usually requires hiding the native element and creating a custom one. Inputs are styled directly.

For checkboxes/radio buttons:

  1. Hide the native element (display: none; or opacity: 0; position: absolute;).
  2. Use pseudo-elements (::before, ::after) or adjacent elements (<label>), to visually display the state (checked/unchecked).
  3. Style the :checked state with a selector like input[type="checkbox"]:checked + label::before or similar.

For text inputs:

  1. Style the border (border, outline).
  2. Adjust internal padding (padding).
  3. Change text color (color) and background (background-color).
  4. Style the placeholder (::placeholder).
  5. Pay special attention to :focus and :disabled states.

Example of styling a checkbox using <label> and a pseudo-element:

/* Hide the native checkbox */
.custom-checkbox input[type="checkbox"] {
  display: none;
}

/* Create a custom indicator */
.custom-checkbox label::before {
  content: ''; /* Necessary for pseudo-elements */
  display: inline-block;
  width: 1em;
  height: 1em;
  border: 1px solid #ccc;
  margin-right: 0.5em;
  vertical-align: middle;
  cursor: pointer;
}

/* Style the "checked" state */
.custom-checkbox input[type="checkbox"]:checked + label::before {
  background-color: blue;
  border-color: blue;
  content: '✓'; /* Or another symbol */
  color: white;
  text-align: center;
  line-height: 1em; /* Align the symbol */
}

/* On hover */
.custom-checkbox label:hover::before {
  border-color: blue;
}

Example of styling a text input:

input[type="text"] {
  padding: 0.5rem;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 1rem;
  transition: border-color 0.3s ease; /* Smooth transition */
}

input[type="text"]:focus {
  outline: none; /* Remove default outline */
  border-color: blue;
  box-shadow: 0 0 5px rgba(0, 0, 255, 0.5); /* Add shadow on focus */
}

input[type="text"]::placeholder {
  color: #999;
}

input[type="text"]:disabled {
  background-color: #eee;
  cursor: not-allowed;
}
How do you style checkboxes and other input elements… - sobes.tech