CSS - Pseudo-class :defined



The CSS pseudo-class selector :defined represents an element that has been defined, using the customElementRegistry.define() method. This includes standard elements, as well as the custom elements.

Syntax

 :defined { /* ... */ } 

CSS :defined Example

Following example demonstrates use of :defined pseudo-class:

 <html> <head> <style> /* standard element p given a background color, whereas custom element has no background-color set */ p { background-color: yellow; font-family: 'Courier New', Courier, monospace; } sample-custom-element { color: blue; } /* Both the standard and custom element is given the font-style as normal, font-weight as 700 and font-family as fantasy */ :defined { font-style: normal; font-weight: 700; font-family: fantasy; } </style> </head> <body> <h3><u>:defined example</u></h3> <sample-custom-element text="Custom element with font color blue and other styles as per the :defined pseudo-class"></sample-custom-element> <p>Standard p element with yellow background, and font as per the :defined pseudo-class</p> <script> customElements.define( "sample-custom-element", class extends HTMLElement { constructor() { super(); let divElem = document.createElement("div"); divElem.textContent = this.getAttribute("text"); let shadowRoot = this.attachShadow({ mode: "open" }).appendChild(divElem); } }, ); </script> </body> </html> 

In the above example:

  • A standard element <p> is given some styling (background-color: yellow; font-family: 'Courier New', Courier, monospace;)

  • A custom element (sample-custom-element) has been declared and is given some styling (color: blue;)

  • Pseudo-class :defined is applied on the defined elements, which has styling specified as (font-style: normal; font-weight: 700; font-family: fantasy;)

  • The output shows that both the elements, standard and custom, takes up the styling specified using the :defined pseudo-class.

Advertisements