CSS Selectors You May Not Know

23 Feb 2017

There are an infinite number of ways to use CSS to create the visual effect that you or your designer is envisioning for your site, but finding the right selector to use for a particular situation can be tricky. Here’s a quick rundown of some useful selectors or selector patterns to keep in your arsenal and some situations that you may want to use them in:

:not()

The :not() selector is an exclusion to your CSS rule. Let’s say you have a .button class that you use throughout the site on <a> anchor tags. If you want to add underlines to anchor tags but not to those anchor tags that are using the button class, then your selector would be

a:not(.button){
 text-decoration: underline;
}


:nth-child()

The :nth-child selector is useful for situations where every nth element needs special styling. One use case would be if we have a series of floated elements and we wanted every 4th element to break to a new row. Then you could do the following

.column{
 float: left;
}
.column:nth-child(3n+1){
 clear: left;
}

In the above situation, with n being 0, 1, 2, etc., the styling would be applied to the first, fourth, 7th column, etc.


+ sibling selector

The + sibling selector is useful for situations where you only want styling if an element comes directly after another element. An example could be if you wanted an h2 heading tag to have different styling only if it comes directly after an h1 tag:

h1 + h2{
 font-weight: normal;
}

Any other h2 headings that do not come directly after an h1 will not have this CSS applied.


> child selector

The > child selector only styles elements that are a direct descendent of the parent element. One area we use this would be in the top main navigation bar.

Sometimes we need to style just the top menu links, but not the links nested in the dropdown menu, so we can do something like this to be more specific about our target elements:

.main-menu > li > a{
  font-size: 2rem;
}


:last-child

We sometimes use :last-child selectors to account for spacing inside of enclosed elements. For example, let’s say you have a panel with 10px of padding. Inside of the panel you have a paragraph tag and all paragraphs on the page have bottom margins. With the :last-child selector you can remove the margin from the last paragraph in your panel. That way the spacing is uniform on all edges:

.panel p:last-child{
 margin-bottom: 0;
}

You could even add more specificity to your selector:

.panel > *:last-child{
 margin-bottom: 0;
}

This finds the last child of that panel, but only if it’s a direct child of the panel parent element. Adding in the * wildcard selector means that this rule will be applied to not just paragraph tags, but to any type of element.


Browser support

These CSS selectors are supported on the latest versions of all major browsers. For specific compatibility information, check out Can I Use?