When creating an HTML form, it may be necessary to dynamically change the requiredness of certain fields based on the value of others. In order to visually indicate this requiredness, you might want to add an asterisk to the label preceding each required field. Rather than directly inserting the asterisk in the HTML or using a script, I would like to achieve this through CSS-defined content.
However, adding visual content before an element can be difficult with CSS selector combinators which primarily go forward, towards children and following siblings. One solution could involve toggling a class name in the label when changing the requiredness of the input field, but that approach separates the two actions into distinct instructions.
Therefore, I have adopted a method where I invert the order of labels and input fields, wrapping them in a
display:flex; flex-direction:column-reverse
element. This allows the label text to be displayed before its corresponding field, enabling the use of a next-sibling combinator to add an asterisk to the label of each required field:
label {
display:inline-flex;
flex-direction:column-reverse;
}
label>input[required]+span:after
{
content:"*";
color:#a21;
}
<label>
<input type="text" required>
<span>Field 1</span>
</label>
<label>
<input type="text">
<span>Field 2</span>
</label>
My concern is how screen readers will interpret this double inversion - once in the HTML and once in the CSS. Will they read the text before prompting for user input?
I always intend to test these scenarios with a screen reader, but finding the time for it seems to be a challenge!