I have the following html form
<div>
<p>Field1</p>
<input type="text" name="fld_one" id="fld_one" value="" />
</div>
<div>
<p>Field2</p>
<input type="text" name="fld_two" id="fld_two" required value="" />
</div>
I want to use CSS to mark required fields like so
div input[required]:before { color: #f00; content: "*"; }
However this css line does not make a visible change in the document.
For reference I was able to modify all required fields with the following:
div input[required] { background-color: #000; }
TL;DR - Can the :before pseudo-class be used with an attribute selector? If so, how?
:before
is a pseudo-element, not a pseudo-class. It can be used with an attribute selector, but you can't use it with input
elements with some browsers because it is a replaced element. (Some browsers, because it's not very well-defined whether they're supposed to work, although most lean toward "no".)
The reason why your attribute selector works is because you're applying styles to the input
element itself, which works consistently in every browser.
Pseudo elements do not work with input
elements, as they have no content.
From the specs:
Authors specify the style and location of generated content with the :before and :after pseudo-elements. As their names indicate, the :before and :after pseudo-elements specify the location of content before and after an element's document tree content. The 'content' property, in conjunction with these pseudo-elements, specifies what is inserted.
Input elements have no childNodes in the DOM, hence, no content property to insert into.
As a possible workaround, apply the stars to the labels instead of the input elements
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With