Is there a way to add a css :hover effect on webcompoenents (not from the parent).
I have following example code
window.customElements.define('a-b', class extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'}).innerHTML = `
<style>
:host {
display: block;
height: 100px;
width: 100px;
background: red;
}
:host:hover {
background: blue;
}
:host::selection {
background: rgba(0, 0, 0, 0.15);
}
</style>
<slot></slot>
`;
}
}
The :host::selection
property works as expected. But the :host:hover
does not seem to have any effect.
I know there are workarounds to this problem like:
div
:hover
effect at the parent stylesheetBut I wanted to know if I am just missing something (since this does not seem too complex) for the sake of cleaner code.
For the sake of cleaner code, use instead the :host()
syntax since :hover
is a pseudo-class applied to the Custom Element. It is then selectable with:
:host(:hover) { ... }
Example:
window.customElements.define('a-b', class extends HTMLElement {
constructor() {
super()
this.attachShadow({mode: 'open'})
.innerHTML = `
<style>
:host(:hover) {
color: white;
background-color: blue;
}
</style>
<slot></slot>`
}
})
<a-b>Hello World</a-b>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With