Skip to content

Advanced CSS Selectors: Examples of Selectors for More Specific styles

Posted on:April 13, 2023 at 11:00 AM

Complex selectors are an important part of CSS that allow developers to target specific elements in unique and powerful ways. One such complex selector is the :not() selector.

The :not() selector is used to select all elements that do not match a given selector. This is particularly useful in situations where you want to style all elements of a certain type, except for one or more specific elements.

For example, let’s say you want to style all paragraphs on your webpage, except for those that are contained within a div with a class of “exclude”. You could use the following CSS selector:

p:not(.exclude) {
  /* styles go here */
}

This selector will style all paragraphs that do not have a class of “exclude”.

Another complex selector that is frequently used is the combination of the child selector (>) and the :last-child selector. This combination is useful when you want to style the last element within a specific parent element.

For example, let’s say you have a list of items, and you want to style the last item in the list. You could use the following CSS selector:

ul > li:last-child {
  /* styles go here */
}

This selector will style the last list item within the unordered list.

Finally, the adjacent sibling selector (+) is another complex selector that allows you to select an element that immediately follows another element. This can be useful in situations where you want to apply a specific style to an element that appears next to another specific element.

For example, let’s say you have a list of items, and you want to style the item that immediately follows a list item with a class of “highlight”. You could use the following CSS selector:

li.highlight + li {
  /* styles go here */
}

This selector will style the list item that immediately follows any list item with a class of “highlight”.

Conclusion

Complex selectors are an important tool for any CSS developer and can be used to select elements in unique and powerful ways. By combining multiple selectors, you can create highly specific styles that will help make your website stand out.

What’s next?

In the coming articles, we will be covering some practical examples of how to use selectors. Don’t forget to follow and share this with your friends that are just starting their web development journey