Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

:required or [required] CSS selector

Browsing the MDN docs to see the status of a proposed pseudo-class, I came across :required (and by extension, :optional). Both of these have been around for a long time but I've only just learnt about them now.

How does this selector differ from using the attribute selector, [required]. Does it differ?

input:required or input[required]. I'll admit that input:optional is nicer than input:not([required]).

If it doesn't differ in any way, which should be used or does it not matter at all? Why were these two introduced when attribute selectors are around?

like image 490
liam-milbel Avatar asked Nov 28 '25 12:11

liam-milbel


1 Answers

input:required {
  border-color: blue;
}

input[required] {
  background-color: pink;
}
<input type="text" required>

Does it differ?

It doesn't really look like they differ functionally.

If it doesn't differ in any way, which should be used or does it not matter at all?

Functionally, I do not think it makes any difference. However,

Why were these two introduced when attribute selectors are around?

Along with pseudo-classes like :valid and :invalid, :required and :optional provide a consistent way to write css for form elements. I believe that was the intended purpose (from no source whatsoever, just my assumption).

As you also mentioned, it does help with reducing verbosity such as :not([required]).

like image 169
cSharp Avatar answered Nov 30 '25 04:11

cSharp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!