The :disabled
pseudo-class targets form elements that have the disabled
attribute set, meaning they cannot be focused, clicked, or otherwise interacted with. This is useful for visually indicating to the user that a form control is not currently available.
Example 1: Styling a Disabled Button
/* This CSS rule targets a button element when it is disabled. */
button:disabled {
/* The background-color property changes the button's color to a light gray. */
background-color: #cccccc;
/* The cursor property changes the mouse pointer to a "not-allowed" symbol. */
cursor: not-allowed;
}
Explanation
This code changes the appearance of a button when it is disabled to provide a clear visual cue that it cannot be clicked. The background becomes gray, and the cursor changes to indicate it's not clickable.
Example 2: Fading Out Disabled Text Inputs
/* This CSS rule targets a text input when it is disabled. */
input[type="text"]:disabled {
/* The opacity property makes the input partially transparent. */
opacity: 0.5;
/* The background-color is changed to a light gray. */
background-color: #f5f5f5;
}
Explanation
This CSS makes disabled text inputs appear faded and with a different background color. This visually separates them from active input fields, improving form clarity.
Example 3: Hiding Labels of Disabled Fields
/* This CSS rule targets the label of a disabled input. */
input:disabled + label {
/* The display property is set to none, hiding the label. */
display: none;
}
Explanation
In some cases, you might want to hide the label of a disabled form field. This code uses the adjacent sibling combinator (+
) to select and hide the label
that immediately follows a :disabled
input.
Example 4: Styling a Disabled Fieldset
/* This CSS rule targets a fieldset element when it is disabled. */
fieldset:disabled {
/* The border property is changed to a dashed gray line. */
border: 1px dashed #ccc;
}
/* This rule styles the legend of a disabled fieldset. */
fieldset:disabled legend {
color: #ccc;
}
Explanation
When a <fieldset>
is disabled, all its descendant form controls also become disabled. This CSS provides a visual cue by changing the border of the fieldset and graying out the text of its <legend>
.
Example 5: Cross-through Text on Disabled Options
/* This CSS rule targets an option within a select element when it is disabled. */
option:disabled {
/* The text-decoration property adds a line-through the text. */
text-decoration: line-through;
color: #999;
}
Explanation
This code styles disabled <option>
elements within a dropdown. The text-decoration: line-through
makes it clear that the option is unavailable for selection.