Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying more in depth selection to the :host CSS pseudo class

I am making a custom element and have been searching for a way of adding more specificity to the :host pseudo class which is associated with the shadow DOM. From my understanding it is used to select the actual custom element itself. For example, if I had an element called my-elem which had a shadow DOM attached the :host pseudo class would be equivalent to a class under my-elem in a global stylesheet.

From this I wanted to try and further specify the selector so that I could style the custom elements on their state, for example: :host:not(.active). However, I cannot really find any reading on further specificity regarding the :host and using the aforementioned does not work.

I have also tried the traditional :host.active and even the cheeky :host[active] however none of them work.

So I wanted to ask if this is even possible. I have done some searching online but there doesn't really seem to be all that much online on the matter and I feel that it may not be possible so I will, possibly have to go a level down and apply the active class to the wrapper of the custom element upon state change.

I just wanted to do it this way as it allows me to programatically style the elements from their parent (I am apply the active/inactive styles to custom slides of a custom element form).

Thank you in advance.

like image 456
MakingStuffs Avatar asked Jan 25 '23 10:01

MakingStuffs


1 Answers

  • :host(.active) is for a Class selector notation:

    <my-element class="active" ></my-element>"

.

  • :host([active]) is for an Attribute selector notation:

    <my-element active="..." ></my-element>"

.

I presume you mean to use the :active Pseudo-Class, like :hover

https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes

Correct syntax:

:host(:active){
  color:yellow;
}

If you also have a :hover in your element:

:host(:hover){
  color:green;
}

you then need to force Specificity (https://css-tricks.com/specifics-on-css-specificity/) with:

:host(:active:active){
  color:yellow;
}

:not notation is then:

:host(:not(:active)){
  color:grey;
}

This of course has higher Specificity than :hover

So to make :hover work again, you need to increase Specificity:

:host(:hover:hover){
  color:green;
}
like image 172
Danny '365CSI' Engelman Avatar answered Feb 01 '23 17:02

Danny '365CSI' Engelman