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?
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]).
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