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:
- Hide the native element (
display: none;oropacity: 0; position: absolute;). - Use pseudo-elements (
::before,::after) or adjacent elements (<label>), to visually display the state (checked/unchecked). - Style the
:checkedstate with a selector likeinput[type="checkbox"]:checked + label::beforeor similar.
For text inputs:
- Style the border (
border,outline). - Adjust internal padding (
padding). - Change text color (
color) and background (background-color). - Style the placeholder (
::placeholder). - Pay special attention to
:focusand:disabledstates.
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;
}