Posted on Leave a comment

Styling a Web Component

This confused me for a bit here so I’m writing it out while it’s fresh in mind. Just because you’re using a web component doesn’t mean the styles of it are entirely isolated. You might have content within a web component that is styled normally along with the rest of your website. Like this:

See the Pen yGaNKr by Chris Coyier (@chriscoyier) on CodePen.

That <whats-up> element isolated the JavaScript-powered functionality of itself by attaching a click handler to the <button> inside of it. But the styling of that button comes from global CSS applied to that page.

But let’s say we move that <button> into the web component, so we can use <whats-up> all by itself. We could do that by .innerHTML‘ing the web component (I suppose because it’s really a “custom element”):

See the Pen Web Component with Global Styles (because no Shadow DOM) by Chris Coyier (@chriscoyier) on CodePen.

Again, entirely styled by the global CSS. Cool. That may be desirable. It also might not be desirable. Perhaps you’re looking to web components to isolate styles for you. Web components can do that via the Shadow DOM. Here’s that same component, using Shadow DOM instead:

See the Pen Web Component with Local Styles by Chris Coyier (@chriscoyier) on CodePen.

Note that the functionality still works (although we had to querySelector<code> through the <code>shadowRoot), but we’ve totally lost the global styling. The Shadow DOM boundry (shadow root) prevents styling coming in or going out (sorta like an iframe).

Shadow Root

There is no global way to penetrate that boundary that I’m aware of, so if you want to bring styles in, you gotta bring them into the template.

See the Pen Web Component with Local Styles by Chris Coyier (@chriscoyier) on CodePen.

This would be highly obnoxious if you both really wanted to use the Shadow DOM but also wanted your global styles. It’s funny that there is a Shadow DOM “mode” for open and closed for allowing or disallowing JavaScript in and out, but not CSS.

If that’s you, you’ll probably need to @import whatever global stylesheets you can to bring in those global styles and hope they are cached and the browser is smart about it in such a way that it isn’t a big performance hit.

I’ll use CodePen’s direct link to CSS feature to import the styles from the Pen itself into the web component:

See the Pen Web Component with Local Styles by Chris Coyier (@chriscoyier) on CodePen.

Another important thing to know is that CSS custom properties penetrate the Shadow DOM! That’s right, they do. You can select the web component in the CSS and set them there:

See the Pen Web Component with Custom Properties by Chris Coyier (@chriscoyier) on CodePen.

The post Styling a Web Component appeared first on CSS-Tricks.

CSS-Tricks

Comments

comments

Leave a Reply

Your email address will not be published. Required fields are marked *