Search code examples
cssweb-componentshadow-domcustom-element

Styling custom HTML elements


I created a vanilla Custom Element:

document.registerElement("my-el", { prototype: Object.create(HTMLElement.prototype) }); 

The element uses Shadow DOM and <style> tags inside it. However, I want to make users define the size of the custom element in the main style sheet. It works by referencing the custom tag, but is this the recommended way to do things like that?

For example:

my-el {
  width: 300px;
  height: 50px;
  background: green;
}

Solution

  • id and class are attributes of HTMLElement. Hence while you use HTMLElement or descendants as custom element’s prototype, you are free to apply class[es] and/or id to it.

    To style the custom element by it’s tag name is definitely fine either, at least while you have the only element of this type on the page (or you want to apply the same style to all of them.)

    Unless you want to give your users an ability to style shadowed DOM (which is in fact possible, but not intended to be done) feel free to deal with custom element the same way as you deal with standard ones.