Subscribe

CSS Pseudo-classes: Other states

✍️

CSS Pseudo classes to manipulate other states a full tutorial [2022]

25 Jan, 2022 Β· 3 min read

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

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

  • :is
  • :not
  • :has

:is

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 cleaner.

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

I 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

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 more details.

:has

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!

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next πŸ“–

Modifying an SVG path with CSS

10 Dec, 2022 Β· 2 min read

Modifying an SVG path with CSS

Animate an SVG path with CSS

9 Dec, 2022 Β· 2 min read

Animate an SVG path with CSS

Join 2097 devs and subscribe to my newsletter