CSS4 Selectors

CSS4 Selectors

Published at

Reading time

A CSS selector is like patterns which are used to select and style the pattern matching elements. We will compare CSS3 with CSS4 selectors and give some examples for better understanding.

Pseudo Class

Pseudo class in CSS is used to defined a special state of an element. Such as visited links have the state of :visited.

CSS3 Selectors

:not() selector

:not pseudo class selector is used to select all the elements except the one which is specified in the argument.

<a href="/" class="link">Link 1</a>
<a href="">No Link</a>
<a href="" rel="nofollow">No Follow</a>
<a href="/" class="link">Link 2</a>

We have 4 <a></a> tags, two with a class link and one with rel attribute and one normal link.

So lets set the color of all the anchor tags to red expect the one's which has class .link.

a:not(.link) {
  color: red;
}

In above code, I don't want to set the color to red for rel="nofollow". But CSS3 :not() selector allows only one argument.

Now let us see in CSS4.

CSS4 Selectors

:not() selector

Allows setting multiple arguments for the :not(selector1, selector2) pseudo class selector.

a:not(.link, [rel='nofollow']) {
  color: red;
}

The above example will let me to set the color of <a></a> tags to red which doesn't have .link class and rel=nofollow attribute.

:matches() selector

Takes multiple arguments and represents an element which is specified in the argument.

Example:

<header>
  <h1>Header Title</h1>
</header>

<h1>General Title</h1>

<div class="container">
  <h1>Container Title</h1>
</div>

<section>
  <h1>Section Title</h1>
</section>

Now I want to change the color of some <h1></h1> tags to green. Normally we write it likes.

// CSS
header h1,
.container h1 {
  color: green;
}

// CSS4
:matches(header, .container) h1 {
  color: green;
}

List of some CSS4 selectors.

SelectorsDoesCSS
:not(s1, s2, s3)Allows multiple arguments3/4
:match(s1, s2)Matches the elements specified in the arugment4
a[href=home i]Case Insensitive (home, HOME, Home etc,.)4
:any-linkMatches source of hyperlink (a, link etc,.)4

Browser Support:

Only 38% of CSS4 selectors are supported by the browsers.

CSS4 Support

Source Browser Selector Test

Conclusion

There are close to 22 new CSS level 4 selectors. Some of them are really cool and let us write less CSS code. But like mentioned above not all the browsers supports the level 4 selectors. Thanks for reading and see you in my next blog post. If you like my post, share it or comment below.

Thanks for reading my blog post 😁

Share this article