CSS :defined Selector

❮ Previous Selectors Next ❯

Meaning

The :defined selector represents any element that has been defined.

This includes any standard element built in to the browser, and custom elements that have been successfully defined.

Version: CSS3




Standard Syntax

:defined {
  css declarations;
}



Browser Support

The numbers in the table specify the first browser version that fully supports the property.




Status







Example

In the following example we define a very simple trivial custom element:

JavaScript

customElements.define(
  "simple-custom",
  class extends HTMLElement {
    constructor() {
      super();

      let divElem = document.createElement("div");
      divElem.textContent = this.getAttribute("text");

      let shadowRoot = this.attachShadow({ mode: "open" }).appendChild(divElem);
    }
  }
);


Then insert a copy of this element into the document, along with a standard <p>:

HTML

<simple-custom text="Custom element example text"></simple-custom>

<p>Standard paragraph example text</p>


In the CSS we first include the following rules:

CSS

/* Give the two elements distinctive backgrounds */
p {
  background: yellow;
}

simple-custom {
  background: cyan;
}

/* Both the custom and the built-in element are given italic text */
:defined {
  font-style: italic;
}

Then provide the following two rules to hide any instances of our custom element that are not defined, and display instances that are defined as block level elements:

CSS

simple-custom:not(:defined) {
  display: none;
}

simple-custom:defined {
  display: block;
}
❮ Previous Selectors Next ❯