Proper way to apply CSS to HTML5 custom elements

You can apply CSS to custom elements just like you can to standard HTML elements.

There’s nothing wrong with scroll-content { ... }, as written in your code.


A Little Background

The browser, at a basic level, has no clue what elements exist. It doesn’t recognize anything… until it is exposed to the default style sheet (sample).

The default style sheet introduces the browser to HTML elements.

Custom elements can therefore be defined as elements that are not included in the default style sheet. (Elements that exist, but are unsupported by the browser, could share this definition.)

Custom elements could, however, be introduced to the browser in author styles.

Here’s something important to consider:

If the browser doesn’t recognize an element (i.e., it’s not in the default style sheet), it will apply CSS initial values.

6.1.1 Specified
values

User agents must first assign a specified value to each property based
on the following mechanisms (in order of precedence):

  1. If the cascade results in a value, use it.

  2. Otherwise, if the property is inherited and the element is not the root of the document tree, use the computed value of the parent
    element.

  3. Otherwise use the property’s initial value. The initial value of each property is indicated in the property’s definition.

As outlined above, if an element is unrecognized (#1 & #2 don’t apply), use the initial value from the property definition (#3 applies).

So in your case:

  • Your custom element is: <scroll-content>

  • Your CSS is: scroll-content { overflow: hidden; }

  • You say in your question that this code does what it’s supposed to do. But unless the framework you mention provides additional styles for custom elements, it cannot work (demo).

Here’s why:

So there’s no way this HTML/CSS combination could work – the overflow property would be ignored, as would height, width and any other properties that don’t apply to inline elements.

A custom element would need to have display: block applied for overflow to work (demo).

Similarly, the only reason body, div, h1, p, ul exist as block elements is because they are defined this way in the default style sheet (sample).

So, putting aside the arguments for and against custom elements, here’s the bottom line:

Add display: block to your custom elements and you’re good-to-go.

Leave a Comment