Home > Software design >  :required or [required] CSS selector
:required or [required] CSS selector

Time:08-03

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?

CodePudding user response:

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

CodePudding user response:

https://developer.mozilla.org/en-US/docs/Web/CSS/:required

The :required CSS pseudo-class represents any <input>, <select>, or <textarea> element that has the required attribute set on it.

Therefore:

:required {
  border: 2px solid #f00;
}

selects:

<input type="text" required />

but doesn't select:

<div required>
test
</div>

Though:

[required] {
  border: 2px solid #f00;
}

selects:

<div required>
test
</div>

Edited

Though a DIV element having a required attribute:

  • Nevertheless, CSS selects it and the element is rendered accordingly. That's a difference.
  • It's possible to make custom elements (Web Components) which might have required attributes. It seems YouTube has several web components. Frameworks, like Vue.js, React.js and Angular support web components. We might use external components with web components.
  • CSS is not only used for HTML. It's also used for XML. For instance, SVG.

https://developer.mozilla.org/en-US/docs/Web/CSS

Cascading Style Sheets (CSS) is a stylesheet language used to describe the presentation of a document written in HTML or XML (including XML dialects such as SVG, MathML or XHTML). CSS describes how elements should be rendered on screen, on paper, in speech, or on other media.

  • Related