10 CSS selectors you shouldn’t code without

Every time we use CSS, we use selectors. But despite this, CSS selectors are one of the more neglected parts of the specification.

We talk about the big transformations in CSS3 but all too often forget the basics. Good use of selectors makes our day-to-day coding simpler and more elegant. Today I’m going to cover the 10 selectors that often slip our minds, but are both effective and highly useful.

 

*

The * selector may be the one you remember most easily but  it’s often underused. What it does is style everything on the page and it’s great for creating a reset and also for creating some page defaults like the font family and size you wish to have.

* {
   margin: 0;
   padding: 0;
   font-family: helvetica, arial, sans-serif;
   font-size: 16px;
}

 

A + B

This selector is called an adjacent selector and what it does is selects the element that is immediately after the first element. If you wanted to select the first div after our header you would type:

header + div {
   margin-top: 50px;
}

 

A > B

This selector will only select the direct children unlike A B that will select any level children of A. This selector is recommended for when you are working with first level children of a parent element. For example if you want to select the first level list items in an unordered list that looks like this:

<ul>
	<li>List Item With ul
		<ul>
			<li>Sub list item</li>
			<li>Sub list item</li>
			<li>Sub list item</li>
		</ul>
	</li>
	<li>List Item</li>
	<li>List Item</li>
</ul>

You would use this selector because the usual A B selector will also selected the list items inside the nested unordered list

ul > li {
   background: black;
   color: white;
}

 

A[href*=”example”]

This is a really good selector for when you want to style a particular link in a different way, whatever is in quotes will be matched against the href of the link. For example to style all links to facebook with the color blue you would use: 

a[href*="facebook"] {
   color: blue;
}

There is also a version without the * that matches the exact url that you can use for exact links.

 

A:not(B)

This selector if particularly useful because of it’s negation clause that allows you to select any group of elements that do not match what you place in B. If you want to select every div except the footer you just need: 

div:not(.footer) {
   margin-bottom: 40px;
}

 

A:first-child  / A:last-child 

The first-child and last-child allow us to select the first and last child of the parent element. This can be a great help when it comes to list items and removing the margin-right or borders. To remove the border in the first list item and the margin in the last list item you need:

ul li:first-child {  
   border: none;  
}     
ul li:last-child {  
   margin-right: 0px;
}     

 

A:nth-child(n)

The nth-child is a simple way for you to select any child of an element by its order. If for example you wanted the third list item in an unordered list this would be the way to go:

ul li:nth-child(3) {
   background: #ccc;
}

We can use nth-child to select every multiplier of a number by using the variable n , for example if we put 3n it would select the list item number 3, 6, 9, 12 and so forth.

 

A:nth-last-child(n)

The nth-last-child works like the nth-child but instead of counting form the first list item it starts counting from the last , so if you use it with the number two it will select the list item that comes before the last one and its usage is just like the nth-child selector:

ul li:nth-last-child(2) {
   background: #ccc;
}

 

A:nth-of-type(n)

This selector does exactly what you think it does; it sees what type of element you placed on it and it selects, for example, the third element on your page that matches what you typed. For selecting the third paragraph in a div you would use:

div p:nth-of-type(3) {
   font-style: italic;
}

 

A:visited

Ever noticed that when you search for something on google the pages you have already seen appear in a different color ? That is exactly what visited does. This is a great addition for the users but it’s sometimes forgotten and by my experience it’s comes in handy every time I search google.

a:visited {
   color: blue;
}

 

Final thoughts

In my experience using these kinds of selectors when coding can save us a lot of time and also avoid the need for a lot of ID’s cluttering up our markup. And this is just the beginning of CSS selectors, there are plenty more selectors that are really handy but sometimes forgotten.

Do you use CSS selectors in your style sheets? Is it easier to fall back on IDs and classes? Let us know in the comments.

Featured image/thumbnail, code image via Shutterstock.

  • Shaunyk

    Sorry for being off subject, but did I miss the post about WDD ditching its recent rebrand for this much nicer, less obtrusive one? I noticed it a while ago and was expecting an explanation of some kind but haven’t seen one yet.
    Just interested that’s all!
    Shaun

    • MattD

      I was thinking exactly the same! Spooky! I’m sure there will be a post about it one day. Or perhaps they’re A/B testing?
      I vote for the new one anyway.

  • Jorge Encarnação

    Great article! It’s worth noting that some of those selectors, like the nth-of-type(n) are only supported in recent versions of IE (9+).

    That said, thanks for this list, I completely forgot about some of them, and it seems to me I’ll be paying a visit to some old projects soon :p

  • http://www.ajw-design.net/ Ashlee J. Williams, Web Design

    The introduction of these selectors is one of my favorite things about CSS3. It cuts down so much on the amount of CSS I need to write.

  • itsjoe

    You should try to avoid using * if you care about rendering performance at all. Moreover, if you want to set font family and size, you should apply it to html and body and let inheritance sort itself out.

    • http://www.blackbookoperations.com/ Black Book Operations

      Indeedero. Resetting stylesheets can be done with html or even body, just as good without any issues. of course, the wildcard selector can be usefull in some situations though. and I guess that, performance wise, it’s not the first on my list to check. (images, heavy scripts, plugins, widgets, …)

    • Sara Vieira

      I always used it for margins and padding but I’ll rethink that , thanks :)

  • dom

    since ie8 support is still relevant for most of our projects all the nth-child first-child and the other useful thingies dont work :( http://www.quirksmode.org/css/selectors/#t55

    • Nick

      There are polyfills/js conditionals for that though!

  • abrishca

    What a great list! It is so easy to forget some of these combinations when you don’t use them on every project.

  • Sara Vieira

    I’m aware of that , I usually use it only for margins but I know a lot of people who use it for setting defaults , I personally use body.

  • Sara Vieira

    Some of them yes bu others no . a:not(selector),nth-child, nth-of-type and ones that follow this pattern only work in IE9 and up.

  • Dave

    Why do you need to use wildcards (*)? Never used one in the 12yrs of front end coding. Still managed to build all the designs that have been thrown at me.

    • http://about.me/evanjacobs Evan Jacobs

      The only times I generally use it are setting box models and blanket child rules (a > *).

      Comes in handy when you’re using inline-block and want all the siblings to have the same vertical orientation and display property.

  • zzzzbov

    Please don’t ever use the asterisk (*) selector. It’s a good way of messing up a lot of styles across a large site without realizing it.

  • Sara Vieira

    Thank you for pointing that out :)

  • lfx

    Nice article! Thank you for sharing!

  • Sdchengvn

    Great ! Thanks!

  • BebopDesigner

    Loved it. And yes, I rely a lot on classes and ids. Thanks for sharing

  • RenderHappy

    The code in this article’s header image would drive me nuts!
    Robot Voice: not … responsive … inline … styles … why … tables … must … fix lol
    Great reminders though!
    To bad IE is always behind a big little chunk.

  • http://lkd.to/bk Bilal Kh

    Thanks a lot! I needed those :)

  • http://www.jamesmarquezblog.com/ James Marquez

    Thanks for the article! There’s a few in here that I had not put much effort to learning. Your article made them very easy to learn and I’ll be implementing them into my future projects.

  • nordic material

    This article contains a couple of dangerous suggestions:
    A:nth-child(n) etc don’t work at all in IE8. which means may people actually should code without.
    How about adding the supported browsers for each one, that way it’s perfectly safe.

  • http://giacomoballi.com/ Giacomo Balli

    good summary :)

  • http://thenickperson.com/ Nicolas McCurdy

    It also has performance issues. Avoid using it if it isn’t needed.

    • aagebmyr

      This is what I have heard as well, surprised it’s not mentioned in the article.

  • Kim

    Good summary of very necessary CSS selectors.

  • CloudyMouse

    Thanks for the info, I have overlooked several and forgotten others. Keep it up! The * selector is something I typically start with to set a font-family and margins, I haven’t run into any issues with inheritance, but maybe I will start setting it using body instead of *.

  • http://www.fasttrackcreations.com/blog Nikhil Malhotra

    Styling the link with A[href*=”example”] is something I found new. Nice!!
    I have also shared few CSS tricky tips on my blog in this article – http://www.fasttrackcreations.com/blog/10-important-css-tricks-to-solve-tricky-issues

    Hope it wont be considered a spam

  • http://bolica.net Ahmed Bolica

    I love CSS3 :)
    Thank you

  • Toufiq

    no way to say awesome . I like this
    toufiq.net

  • Sara Vieira

    I am aware that :visited is very old , it’s not from CSS3 but it’s a selector that I rarely see put to good use and it’s something that really helps accessibility.

  • http://thewebivore.com/ Pam Selle

    * (universal) is a horribly selector performance-wise. Ouch!

  • Legomushroom

    Great! :nth-last-of-type(n) should be mentioned I suppose. Thanks!

  • StudentWebHosting

    Nice. You’ve inspired me to create my own post about css3 selectors!

  • designfreakme

    Very informative post, thanks.