Peer States
React to a sibling's state with peer.
Syntax
sibling: class="peer" target: class="peer-focus:visible"Mark an element peer, then a later sibling can respond to its state with peer-*. A common use is showing a message when an input is focused or invalid.
Example
Loading editorβ¦
Press Run to see the result.
When to use it
- A developer shows a validation error message below a text input by marking the input as peer and using peer-invalid:block on the hidden error div.
- A custom checkbox label changes its text color when the checkbox is checked by using peer on the input and peer-checked:text-indigo-600 on the label.
- A text area's character counter turns red when the textarea has the 'invalid' state using peer-invalid:text-red-500 on the sibling count span.
More examples
Show error on peer-invalid
peer on the input exposes its :invalid CSS state; peer-invalid:block on the sibling paragraph shows the error without any JavaScript.
<input
type="email"
class="peer border rounded px-3 py-2 w-full"
placeholder="Email address"
required
/>
<p class="hidden peer-invalid:block text-sm text-red-600 mt-1">
Please enter a valid email address.
</p>Styled custom checkbox
The hidden checkbox is marked peer; its checked state styles the adjacent custom box and label text via peer-checked: variants.
<label class="flex items-center gap-2 cursor-pointer">
<input type="checkbox" class="peer sr-only">
<div class="w-4 h-4 border-2 border-gray-400 rounded
peer-checked:bg-indigo-600 peer-checked:border-indigo-600">
</div>
<span class="peer-checked:text-indigo-700 font-medium">I agree</span>
</label>Focus-based sibling highlight
peer-focus on the button changes the search icon color to match the active state when the sibling input receives focus.
<div class="flex items-center border rounded overflow-hidden
focus-within:ring-2 focus-within:ring-indigo-500">
<input
type="text"
class="peer flex-1 px-3 py-2 outline-none"
placeholder="Search"
/>
<button class="px-3 py-2 text-gray-400 peer-focus:text-indigo-600">
Search
</button>
</div>
Discussion