Is there a way to style a webcomponent based on the container it's in?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Is there a way to style a webcomponent based on the container it's in?



I'm trying to write some webcomponents that respond to a theme for the container they're in. I.e.


<div dataset-theme='light'>
<my-custom-element></my-custom-element>
</div>

<div dataset-theme='dark'>
<my-custom-element></my-custom-element>
</div>



I'd like the background color of the one in the dark theme to change to a dark color. I've tried CSS like the following inside of my shadow-root:


[dataset-theme='dark']
:host
background-color: #333



But it doesn't seem to respond to that at all. Is there a way for the style of a webcomponent to change based on the container it's in?





Have you tried [dataset-theme='dark'] my-custom-element{background-color: #333}?
– Justinas
Jul 18 at 7:09


[dataset-theme='dark'] my-custom-element{background-color: #333}




3 Answers
3



You can try like this


CSS :

div[dataset-theme='dark'] my-custom-element{
background-color : #333;
}



It's may be work.



The :host-context() CSS pseudo-class will allow you to style the custom element depending on its context.


:host-context()


:host-context( [dataset-theme='dark'] ) {
background-color: #333
}



As a complement, you can use :host to apply some default CSS style when the context is not defined.


:host



Below a demo:




customElements.define( 'my-custom-element', class extends HTMLElement {
constructor () {
super()
this.attachShadow( { mode: 'open' } )
.innerHTML = `<style>
:host-context([dataset-theme="dark"]) {
background-color: darkblue ;
color: lightgray ;
}
:host-context([dataset-theme="light"]) {
background-color: lightyellow ;
color: orange ;
}
:host {
background-color: white ;
color: black ;
}
</style>
<slot>No</slot> Theme`
}
} )


<div dataset-theme='light'>
<my-custom-element>Light</my-custom-element>
</div>

<div dataset-theme='dark'>
<my-custom-element>Dark</my-custom-element>
</div>

<div>
<my-custom-element></my-custom-element>
</div>



Try to write simple css for the same. As you may have created that component somewhere. Hence it'll function as regular html tags.


CSS :

my-custom-element {
background-color : red;
}






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Arduino Mega cannot recieve any sketches, stk500_recv() programmer is not responding

Visual Studio Code: How to configure includePath for better IntelliSense results

C++ virtual function: Base class function is called instead of derived