Ad/iklan :







Search.Pencarian Menu

Add text send email to rh3252705.adda@blogger.com or Click this (Text porn Will delete) | Tambah teks kirim email ke rh3252705.adda@blogger.com atau Klik ini (Teks porno akan dihapus)
Total post.pos : 13631+

[Go Make Things] Styling the shadow DOM with CSS variables in Web Components

For the last week, we've been looking at why styling elements in the shadow DOM sucks so bad, and what to do about it.

So far, we've looked at using inline styles and external stylesheets loaded into the shadow DOM.

Today, let's talk about CSS variables.

Our example element

Just to recap, we have a <count-up> element, like this…

<count-up></count-up>

Which, when the Web Component JavaScript loads, renders HTML like this…

<count-up>  	#shadow-root (closed)  		<button>Clicked 0 Times</button>  </count-up>

And it's styled to look like this…

// Inject the HTML into the shadow DOM  this.root.innerHTML =   	`<style>  		button {  			background-color: rebeccapurple;  			border: 0;  			border-radius: 0.25em;  			color: white;  			font-family: 'PT Serif', sans-serif;  			font-size: 1.2em;  			padding: 0.25em 0.5em;  		}  	</style>  	<button>Clicked ${this.count} Times</button>`;  

Currently, the only way for a developer to change the styles of those elements is by directly modifying the Web Component's JS. Let's fix that!

CSS variables can be accessed from the light DOM

While global CSS does not cascade into the Shadow DOM, CSS variables do!

If you want to give developers the ability to style certain aspects of your web component, but not everything, CSS variables (officially called custom properties) provide a useful way to do that.

We can update our inline styles to use CSS variables.

Here, I'm also passing a fallback value into the var() method that will be used as a default value if the named CSS variable doesn't exist.

// Inject the HTML into the shadow DOM  this.root.innerHTML =   	`<style>  		button {  			background-color: var(--bg-color, rebeccapurple);  			border: var(--border, 0);  			border-radius: var(--border-radius, 0.25em);  			color: var(--color, white);  			font-family: var(--font, 'PT Serif', sans-serif);  			font-size: var(--font-size, 1.2em);  			padding: var(--padding, 0.25em 0.5em);  		}  	</style>  	<button>Clicked ${this.count} Times</button>`;  

In my global stylesheet, I can now modify all of these properties using CSS variables on my count-up element.

If I want to style different web components uniquely, I can even target them more specifically by class, ID, or an attribute like [start-value].

count-up {  	--bg-color: #0088cc;  	--border-radius: 0;  }    count-up[start-value="42"] {  	--bg-color: azure;  	--color: #272727;  	--border-radius: 1em;  }

Cheers,
Chris

Want to share this with others or read it later? View it in a browser.

Share :

Facebook Twitter Google+
0 Komentar untuk "[Go Make Things] Styling the shadow DOM with CSS variables in Web Components"

Back To Top