Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

:required — required form controls

The CSS :required pseudo-class selects controls that HTML defines as required. It describes a requirement on a field, not whether its current value is valid or whether the field is empty.

Version: CSS modules; structured CSSWG indexes reconciled with pinned MDN BCD; Chromium 152 scope gate, per-example verification still required

Syntax

:required { /* declarations */ }

The :required pseudo-class lets you style required controls. In HTML, it matches required input elements and select and textarea elements with a required attribute. It takes no arguments; input:required restricts matching to input elements.

It is not equivalent to [required]: the attribute selector checks only whether the attribute is present, whereas :required respects the element's semantics. Adding the attribute to an arbitrary element does not make it a required control. :optional describes optional controls, not every remaining element in the document.

Requiredness and validity are separate states. A completed field still matches :required; use :valid and :invalid to select by validity. The example matches both the filled email and the empty note, but not the optional nickname. Do not interpret the border as an error message: the text labels communicate the requirement separately.

Examples

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>:required example</title>
<style>
  :required { border: 2px solid #805000; }
</style>
<form id="demo">
  <p><label>Email (required): <input id="email" type="email" required value="ada@example.com"></label></p>
  <p><label>Note (required): <textarea id="note" required></textarea></label></p>
  <p><label>Nickname (optional): <input id="nickname" type="text"></label></p>
</form>
<pre id="result"></pre>
<script>
  const ids = Array.from(
    document.querySelectorAll('#demo :required'),
    element => element.id
  );
  document.getElementById('result').textContent = ids.join(', ');
</script>
</html>

Result

email, note

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources