CSS Trick
Dynamic Form Labels with :has()
Auto-add asterisks to required fields and '(optional)' to optional ones.
#css
#forms
#has-selector
#accessibility
Browser Support
✓ Chrome 105+
✓ Firefox 121+
✓ Safari 15.4+
✗ Edge
Dynamic Form Labels
Use :has() to automatically mark required and optional fields.
label:has(+ input:required)::after { content: " *"; color: red;}
label:has(+ input:optional)::after { content: " (optional)"; color: #777;}Live Demo
Auto Labels
:has()
#ef4444
#888888
CSS Code
.form-demo { display: flex; flex-direction: column; gap: 0.75rem; width: 100%; max-width: 260px; } .form-field { display: flex; flex-direction: column; gap: 0.25rem; } .form-label { font-size: 0.875rem; } .form-label:has(+ input:required)::after { content: " *"; color: #ef4444; } .form-label:has(+ input:not([required]))::after { content: " (optional)"; color: #888888; font-size: 0.75rem; } .form-input { width: 100%; padding: 0.5rem; border-radius: 0.375rem; border: 1px solid rgba(139, 92, 246, 0.3); background: rgba(255, 255, 255, 0.05); color: inherit; font-size: 0.875rem; } .form-input:focus { outline: 2px solid rgba(139, 92, 246, 0.5); outline-offset: 2px; }
Labels are auto-generated based on input’s required attribute - no manual markup needed.