Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

:before with an attribute selector

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?

like image 566
Mr Griever Avatar asked Dec 08 '22 21:12

Mr Griever


2 Answers

: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.

like image 181
BoltClock Avatar answered Feb 24 '23 04:02

BoltClock


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

like image 32
Madara's Ghost Avatar answered Feb 24 '23 04:02

Madara's Ghost