CSS Pseudo-classes: Other states

β€” 4 minute read

permalink

This is the last series in the CSS pseudo-class exploration. These are pseudo-classes that did not fit any of the previous categories.

I've split this up into a series of four, where this is the last part about other pseudo-states.

The other parts:

Other state selectors permalink

As for the other ones, we have the following that we can explore.

  • :is
  • :not
  • :has

:is permalink

This selector can be used to match multiple elements on the go.

You might have seen the following in standards CSS before:

div strong,
div i
{
color: hotPink;
}

This will make all strong and italic elements in a div pink. However, we can leverage the :is selector to make this a bit more cleaner.

div :is(strong, i) {
color: hotPink;
}

I really like this selector and have been using it more lately. It cleans up classes.

Try it out in this CodePen.

See the Pen `:is` by Chris Bongers (@rebelchris) on CodePen.

:not permalink

Much like the above :is selector, this one does the opposite and fires if it's NOT one of the mentioned elements.

We want to style all elements, but the strong and italic ones.

div :not(strong, i) {
color: hotPink;
}

And another cool thing we can do with this selector is validating on even more queries.

img:not([alt]) {
outline: 10px solid red;
}

The above example will put a big red outline around images missing the alt attribute.

Note: check out this article for more information about CSS attribute selectors

Try both out in this CodePen.

See the Pen `:is` by Chris Bongers (@rebelchris) on CodePen.

I also have a complete article on the CSS :not selector if you want some more details.

:has permalink

This is not a stable solution yet, but super excited this is coming out!

So far, you can only use this in the Safari Technology preview version. But it's super exciting to see what we can do with it.

We can target a parent that contains certain children.

div:has(p) {
background: yellow;
}

This would select all divs that have paragraph elements.

Some use-cases would be to remove margin from a header if it has a subtitle, for instance:

.header {
margin: 1;
}
.header:has(.subtitle) {
margin: 0;
}

Keep an eye out for this one, as it will become a big change for what we can do with CSS.

Thank you for reading, and let's connect! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter