Awesome CSS pseudo-classes

ยท

2 min read

I think we've established the fact that CSS is weird, annoying and makes you want to cry sometimes๐Ÿ™‚๐Ÿ’”. In today's episode, we'll be looking at CSS pseudo-classes, but not just any psuedo-class. I've come across some really interesting ones that are not talked about enough and should really be a part of your code montage especially as a novice(to give you that senior developer feel, ya get?๐ŸŒš).

If that sounds interesting, let's jump right in!

Disclaimer: Some of these may make you cry even more, so grab a tissue.

Let's begin shall we!

:invalid

This is used to style an <input> when it is invalid, for example when specify <input type="number"> and you type in text, the input is invalid.

invalid.png The :invalid pseudoclass in action

:disabled

The :disabled pseudoclass is used to style a <button> when the disabled attribute is set to true.

disabled.png

:first-of-type/:last-of-type

This is used when you want to style the first/last of a particular element, for example

first of type.png :first-of-type

last-of-type.png :last-of-type

:is() ๐Ÿ˜…

The :is() psuedo-class is used to style every element that matches the argument provided in the parantheses, for example

:is(ul, ol){
  color: red;
}

This would style every ol and ul with the red color.

is.png You can gain much more from the :is() pseudo-class when you try to style multiple children/descendants at once, as shown above.

Traditionally if we wanted to style the last list item of both ol and ul, we would have to do this

ul > li:last-of-type, ol > li:last-of-type {
  color: red;

The first one seems much nicer, doesn't it๐Ÿ˜

:has() ๐Ÿ˜…

The :has() pseudo-class is used to style descendants of a particular element or possibly style a sibling element. Previously, if we wanted to style multiple descendants of an element, we would have to select each descendant separately, like this

has-old.png.

But now, we can use the :has(), to select both elements together has.png.

To style a sibling element, use the "+" operator together with the :has() pseudo-class, for example

<div>
     <h1>Hello!</h1>
     <h2>How are you</h2>
</div>
 h1:has(+ h2){
  color: red;
}

*๐Ÿ˜… means the pseudo-class is not fully supported by all browsers, like Samsung Internet and Firefox(Android and Desktop)

That's all for this week. Don't forget to leave a like or a reaction and if you want to see related content, do give me a follow. Thank you!๐Ÿ˜„

ย