Skip to main content

Command Palette

Search for a command to run...

The :not() CSS pseudo-class - CSS trick ๐Ÿ˜

Updated
โ€ข2 min read
The :not() CSS pseudo-class - CSS trick ๐Ÿ˜
M

Passionate about building products and making impacts through tech

Software Development is one of those professions that require constant and endless learning, just as soon as you finish learning a concept another pops up ๐Ÿ˜…

Today I want to share with you a handy CSS trick that not only saves time during development but reduces the amount of CSS you would normally write and this is the CSS :not() pseudo-class

Just for reference, this is the definition of a pseudo-class by MDN

A pseudo-class is a selector that selects elements that are in a specific state, e.g. they are the first element of their type, or they are being hovered over by the mouse pointer. They tend to act as if you had applied a class to some part of your document, often helping you cut down on excess classes in your markup, and giving you more flexible, maintainable code.

:not () syntax definition from MDN Web docs

The :not() CSS pseudo-class represents elements that do not match a list of selectors. Since it prevents specific items from being selected, it is known as the negation pseudo-class

What this pseudo-class basically does is set an exception for a particular class or selector which is not to be styled, a quick example to explain the above statement -

/* Selects all elements that is not an Image */
:not(img) {
  font-size: 32px;
}

And I find this specifically useful when creating a navbar as in the example below

/* Set a margin-left of 10px to all list items ('li' tag) except the last li */
li:not(:last-child) {
  margin-left: 10px;
}

Read more about it on the official MDN Web docs here

Hope this helps someone write better code, follow me for more posts on web development

More from this blog

Lekandev's Hideout

6 posts

I am an idealistic teenager, frontend developer with skills on JavaScript, React and MERN stack. I tend to have major, original ideas to create the next big thing.