I am writing an HTML form in which the requiredness of some fields depends on the value of others and thus changes dynamically. I would like to present a visual cue of that requiredness by appending an asterisk to the label preceding each required field. Since it is purely visual and the semantics of the situation are well expressed by the required
attribute in the appropriate tag, I would like the asterisk to be added as content from a CSS definition rather than inserting it in the HTML directly or via script.
However, adding visual content to an element preceding the required field is challenging, since CSS selector combinators seem to go forward (towards children and following siblings) but not backwards (towards parents or previous siblings).
I could of course toggle a class name in the label from the same code where I change the requiredness of the input field, but that would separate the content addition from the requiredness change into two different instructions that I would have to remember to call together, now and a year from now, so that is a constraint I would like to avoid; I would prefer toggling the requiredness of the input field and have the CSS react to that change without further involvement on my part.
So I have resorted to inverting the order of each label and its input field, and then wrapping both in a display:flex; flex-direction:column-reverse
element, making the label text be rendered before its corresponding field despite being declared after it. That way, I can use a next-sibling combinator to add an asterisk to the label text 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 question, however, is how will screen readers interpret that double inversion (once in the HTML and once in the CSS). Will they read out the text before expecting a user input?
Thanks, I always have the need to sit down, install a screen reader and find out these things by myself, but I never seem to have the time to do it :-(