Sub topic 8
Styling form state: :checked, :disabled, :required, :invalid, :placeholder-shown
This chapter covers the pseudo-classes that react to the state of form controls. It assumes you know basic HTML form elements and attributes, CSS rule syntax, and attribute and sibling selectors. It also assumes you know the difference between a pseudo-class and a pseudo-element from the earlier chapter on syntax.
Why form state is different
Most pseudo-classes you have met so far depend on user input events (:hover) or on position in the tree (:first-child). Form pseudo-classes depend on the state of the control itself. That state comes from three places:
- HTML attributes you write, such as
required,disabled, andchecked. - The user's current input, such as a typed value or a ticked box.
- Constraint validation, where the browser compares the value against rules such as
required,type="email",pattern,min, andmaxlength.
The browser keeps these states up to date. Your CSS only describes how each one looks, and no JavaScript is needed.
| Pseudo-class | Matches when |
|---|---|
| `:checked` | A checkbox or radio button is ticked, or an `<option>` is selected |
| `:disabled` | The control has the `disabled` attribute, or sits inside a disabled `<fieldset>` |
| `:enabled` | The control can be used (the opposite of `:disabled`) |
| `:required` | The control has the `required` attribute |
| `:optional` | A form control that is not required |
| `:valid` | The value passes constraint validation |
| `:invalid` | The value fails constraint validation |
| `:placeholder-shown` | The control is displaying its placeholder text |
:checked and the sibling trick
A checkbox is tiny and hard to restyle directly. A common technique is to style the label that follows it. The + combinator selects the next sibling, so the label can react to the checkbox state.
input:checked + label {
font-weight: 600;
}This only works when the label comes after the input in the HTML:
<input type="checkbox" id="news" name="news">
<label for="news">Send me the newsletter</label>If your markup puts the label first, + cannot reach backward. Either reorder the markup or use :has(), covered in the logical pseudo-classes chapter, as in label:has(input:checked).
:checked also matches a selected <option>, but browsers limit which properties they apply to dropdown options, so do not rely on it for heavy styling.
A related state is :indeterminate. A checkbox can be set to indeterminate from JavaScript (input.indeterminate = true) to show a "some selected" state. It is neither checked nor unchecked in appearance, so :checked does not match it unless the box is also checked.
:disabled and :enabled
A disabled control cannot be focused, edited, or submitted. Browsers already dim it, but you often want a consistent look.
input:disabled,
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}A <fieldset disabled> disables every control inside it. Each of those controls matches :disabled, but the fieldset itself also matches. Style the controls, not the container, unless you want the whole group dimmed.
Low opacity can drop text contrast below readable levels. Dimming is acceptable for disabled controls under WCAG, which exempts inactive components from contrast requirements. Still, avoid making the text so faint that users cannot tell what the control is for.
A common mistake is using :disabled on a link. An <a> element is not a form control, so it never matches :disabled. For links, use [aria-disabled="true"] and handle the behavior yourself.
:required and :optional
:required matches controls that carry the required attribute. A typical use is marking mandatory fields with generated content on the label:
input:required {
border-left: 4px solid #1a73e8;
}Because :required and :optional reflect markup, they do not change as the user types. The required attribute only applies to <input>, <select>, and <textarea>.
:valid and :invalid
:invalid matches when the current value fails constraint validation. The rules come from attributes, so the CSS stays short:
<input type="email" id="email" required placeholder="[email protected]">Here the field is invalid when it is empty (because of required) and also when the text is not a well-formed email address.
The pitfall is timing. A required field starts empty, so it is invalid from the moment the page loads. A rule like input:invalid { border-color: #c00; } paints every empty required field red before the user has done anything. That is hostile and confusing.
Waiting for input with :placeholder-shown
:placeholder-shown matches while the placeholder text is visible, which means the field is empty. Negating it means "the user has typed something". Combined with :invalid, you get errors only after typing begins:
input:required:invalid:not(:placeholder-shown) {
border-color: #c00;
}
input:disabled {
opacity: 0.5;
}
input:checked + label {
font-weight: 600;
}This only works if the input has a placeholder attribute. Without one, :placeholder-shown never matches, so :not(:placeholder-shown) always matches and you are back to showing errors on empty fields. If you do not want visible placeholder text, a single space works as a hidden trigger (placeholder=" "), though it is a workaround and a real placeholder is better for users.
The chain also has a gap. Once the user types something and then deletes it, the field is empty again, so :placeholder-shown matches and the error disappears. That is usually acceptable, but be aware of it.
A fuller example
This page combines the states. Save it and open it in a browser:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Form state demo</title>
<style>
label { display: block; margin-top: 1rem; }
input { padding: 0.4rem; border: 2px solid #767676; }
input:required { border-left-width: 6px; }
input:required:invalid:not(:placeholder-shown) { border-color: #c00; }
input:required:valid { border-color: #2e7d32; }
input:disabled { opacity: 0.5; cursor: not-allowed; }
input:checked + label { font-weight: 600; }
input[type="checkbox"] + label { display: inline; }
</style>
</head>
<body>
<form>
<label for="email">Email (required)</label>
<input type="email" id="email" required placeholder="[email protected]">
<label for="code">Promo code (not available)</label>
<input type="text" id="code" disabled>
<input type="checkbox" id="terms">
<label for="terms">I accept the terms</label>
</form>
</body>
</html>Typing abc in the email field turns the border red. Typing [email protected] turns it green. Clearing it removes both colors.
How the states change over time
A control moves between valid and invalid as the user edits it. The diagram shows the email field above.
The Empty state is invalid to the browser, but your CSS treats it as neutral because of :not(:placeholder-shown).
Edge cases and gotchas
- Color alone is not enough. A red border is invisible to some users with color vision deficiency. Add an icon, text, or a message tied to the field with
aria-describedby. :user-invalidis the newer option. It matches an invalid control only after the user has interacted with it, which solves the timing problem without the placeholder trick. Support has grown across current browsers, but check compatibility tables before depending on it.:validon optional empty fields. An empty optional field is valid. A rule likeinput:valid { border-color: green; }turns every untouched optional field green. Pair it with:requiredor:not(:placeholder-shown).- Custom validity. If JavaScript calls
setCustomValidity("message")with a non-empty string, the control becomes:invaliduntil the message is cleared with an empty string. - Forms with
novalidate. This attribute stops the browser from blocking submission, but:invalidand:validstill match. Your styles keep working. - Radio groups. If any radio button in a named group has
required, every button in the group is:invaliduntil one is selected. - Specificity. Each pseudo-class adds the weight of a class selector.
input:required:invalid:not(:placeholder-shown)has a higher specificity thaninput.error, so a later class rule may lose.
Exercises
Exercise
A required text input has no placeholder attribute. You write input:required:invalid:not(:placeholder-shown) { border-color: #c00; }. When does the red border appear, and how do you fix it?
Show answer
The border appears immediately on page load, even when the field is empty. Without a placeholder, :placeholder-shown never matches, so :not(:placeholder-shown) always matches, and an empty required field is invalid. Fix it by adding a placeholder attribute (for example placeholder=" " if you want it hidden) or by using :user-invalid where supported.
Exercise
Write a rule that makes a checkbox label bold when the checkbox is ticked, and state the one markup requirement for it to work.
Show answer
input[type="checkbox"]:checked + label { font-weight: 600; }. The label must be the next sibling that directly follows the checkbox in the HTML. If the label comes first, use label:has(input:checked) instead.