Universal selector, how to exclude some elements

css, css-selectors

Solution

If you want to exclude root elements like `html`/`body`, you could select all elements within them.

In this case, any of the following would work:

html body *:hover { background-color: yellow }
body *:hover { background-color: yellow }
* * *:hover { background-color: yellow }
:root * *:hover { background-color: yellow }

To exclude other elements, you could use the `:not()` pseudo-class to negate them.

For instance, you could add an `.excluded` class to the elements.

html body *:not(.excluded):hover { background-color: yellow }

This will be problematic, though, because the universal selector will be applied to all elements, including elements nested within the `.excluded` elements.

If there are any nested elements within the `body` element, the `background-color` will inadvertently appear to be applied to children elements even if they contain the `.excluded` class merely because the `background-color` is added to the parent element.

You could consider using the direct child combinator, `>` to prevent this to a degree.

html body > *:not(.excluded):hover { background-color: yellow }

Of course, this assumes you only want the `background-color` applied to direct children in the `body` element.

In conclusion, you should therefore avoid using the universal selector when possible.

Problem

After building a blog last part is to make a universal selector that when hover over it will highlight the elements yellow. however we need to exclude elements like body and html from that behavior. i starter with this ``` *:hover { background-color:yellow } ``` How can I exclude elements from universal selector?

Original source