The 30 CSS Selectors you Must Memorize

The 30 CSS Selectors you Must Memorize

Tutorial Details
  • Topic: CSS selectors
  • Difficulty: Intermediate
This entry is part 2 of 16 in the CSS3 Mastery Session
« PreviousNext »

Twice a month, we revisit some of our readers’ favorite posts from throughout the history of Nettuts+. This tutorial was first published in November, 2010.

So you learned the base id, class, and descendant selectors – and then called it a day? If so, you’re missing out on an enormous level of flexibility. While many of the selectors mentioned in this article are part of the CSS3 spec, and are, consequently, only available in modern browsers, you owe it to yourself to commit these to memory.


1. *

* {
 margin: 0;
 padding: 0;
}   

Let’s knock the obvious ones out, for the beginners, before we move onto the more advanced selectors.

The star symbol will target every single element on the page. Many developers will use this trick to zero out the margins and padding. While this is certainly fine for quick tests, I’d advise you to never use this in production code. It adds too much weight on the browser, and is unnecessary.

The * can also be used with child selectors.

#container * {
 border: 1px solid black;
}   

This will target every single element that is a child of the #container div. Again, try not to use this technique very much, if ever.

View Demo

Compatibility

  • IE6+
  • Firefox
  • Chrome
  • Safari
  • Opera

2. #X

#container {
   width: 960px;
   margin: auto;
}   

Prefixing the hash symbol to a selector allows us to target by id. This is easily the most common usage, however be cautious when using id selectors.

Ask yourself: do I absolutely need to apply an id to this element in order to target it?

id selectors are rigid and don’t allow for reuse. If possible, first try to use a tag name, one of the new HTML5 elements, or even a pseudo-class.

View Demo

Compatibility

  • IE6+
  • Firefox
  • Chrome
  • Safari
  • Opera

3. .X

.error {
  color: red;
}   

This is a class selector. The difference between ids and classes is that, with the latter, you can target multiple elements. Use classes when you want your styling to apply to a group of elements. Alternatively, use ids to find a needle-in-a-haystack, and style only that specific element.

View Demo

Compatibility

  • IE6+
  • Firefox
  • Chrome
  • Safari
  • Opera

4. X Y

li a {
  text-decoration: none;
}   

The next most comment selector is the descendant selector. When you need to be more specific with your selectors, you use these. For example, what if, rather than targeting all anchor tags, you only need to target the anchors which are within an unordered list? This is specifically when you’d use a descendant selector.

Pro-tip – If your selector looks like X Y Z A B.error, you’re doing it wrong. Always ask yourself if it’s absolutely necessary to apply all of that weight.

View Demo

Compatibility

  • IE6+
  • Firefox
  • Chrome
  • Safari
  • Opera

5. X

a { color: red; }
ul { margin-left: 0; }   

What if you want to target all elements on a page, according to their type, rather than an id or classname? Keep it simple, and use a type selector. If you need to target all unordered lists, use ul {}.

View Demo

Compatibility

  • IE6+
  • Firefox
  • Chrome
  • Safari
  • Opera

6. X:visited and X:link

a:link { color: red; }
a:visted { color: purple; }   

We use the :link pseudo-class to target all anchors tags which have yet to be clicked on.

Alternatively, we also have the :visited pseudo class, which, as you’d expected, allows us to apply specific styling to only the anchor tags on the page which have been clicked on, or visited.

View Demo

Compatibility

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

7. X + Y

ul + p {
   color: red;
}   

This is referred to as an adjacent selector. It will select only the element that is immediately preceded by the former element. In this case, only the first paragraph after each ul will have red text.

View Demo

Compatibility

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

8. X > Y

div#container > ul {
  border: 1px solid black;
}   

The difference between the standard X Y and X > Y is that the latter will only select direct children. For example, consider the following markup.

   <div id="container">
      <ul>
         <li> List Item
           <ul>
              <li> Child </li>
           </ul>
         </li>
         <li> List Item </li>
         <li> List Item </li>
         <li> List Item </li>
      </ul>
   </div>

A selector of #container > ul will only target the uls which are direct children of the div with an id of container. It will not target, for instance, the ul that is a child of the first li.

For this reason, there are performance benefits in using the child combinator. In fact, it’s recommended particularly when working with JavaScript-based CSS selector engines.

View Demo

Compatibility

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

9. X ~ Y

ul ~ p {
   color: red;
}

This sibling combinator is similar to X + Y, however, it’s less strict. While an adjacent selector (ul + p) will only select the first element that is immediately preceded by the former selector, this one is more generalized. It will select, referring to our example above, any p elements, as long as they follow a ul.

View Demo

Compatibility

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

10. X[title]

a[title] {
   color: green;
}   

Referred to as an attributes selector, in our example above, this will only select the anchor tags that have a title attribute. Anchor tags which do not will not receive this particular styling. But, what if you need to be more specific? Well…

View Demo

Compatibility

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

11. X[href="foo"]

a[href="http://net.tutsplus.com"] {
  color: #1f6053; /* nettuts green */
}

The snippet above will style all anchor tags which link to http://net.tutsplus.com; they’ll receive our branded green color. All other anchor tags will remain unaffected.

Note that we’re wrapping the value in quotes. Remember to also do this when using a JavaScript CSS selector engine. When possible, always use CSS3 selectors over unofficial methods.

This works well, though, it’s a bit rigid. What if the link does indeed direct to Nettuts+, but, maybe, the path is nettuts.com rather than the full url? In those cases we can use a bit of the regular expressions syntax.

View Demo

Compatibility

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

12. X[href*="nettuts"]

a[href*="tuts"] {
  color: #1f6053; /* nettuts green */
}   

There we go; that’s what we need. The star designates that the proceeding value must appear somewhere in the attribute’s value. That way, this covers nettuts.com, net.tutsplus.com, and even tutsplus.com.

Keep in mind that this is a broad statement. What if the anchor tag linked to some non-Envato site with the string tuts in the url? When you need to be more specific, use ^ and &, to reference the beginning and end of a string, respectively.

View Demo

Compatibility

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

13. X[href^="http"]

a[href^="http"] {
   background: url(path/to/external/icon.png) no-repeat;
   padding-left: 10px;
}   

Ever wonder how some websites are able to display a little icon next to the links which are external? I’m sure you’ve seen these before; they’re nice reminders that the link will direct you to an entirely different website.

This is a cinch with the carat symbol. It’s most commonly used in regular expressions to designate the beginning of a string. If we want to target all anchor tags that have a href which begins with http, we could use a selector similar to the snippet shown above.

Notice that we’re not searching for http://; that’s unnecessary, and doesn’t account for the urls that begin with https://.

Now, what if we wanted to instead style all anchors which link to, say, a photo? In those cases, let’s search for the end of the string.

View Demo

Compatibility

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

14. X[href$=".jpg"]

a[href$=".jpg"] {
   color: red;
}   

Again, we use a regular expressions symbol, $, to refer to the end of a string. In this case, we’re searching for all anchors which link to an image — or at least a url that ends with .jpg. Keep in mind that this certainly won’t work for gifs and pngs.

View Demo

Compatibility

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

15. X[data-*="foo"]

a[data-filetype="image"] {
   color: red;
}   

Refer back to number eight; how do we compensate for all of the various image types: png, jpeg,jpg, gif? Well, we could create multiple selectors, such as:

a[href$=".jpg"],
a[href$=".jpeg"],
a[href$=".png"],
a[href$=".gif"] {
   color: red;
}   

But, that’s a pain in the butt, and is inefficient. Another possible solution is to use custom attributes. What if we added our own data-filetype attribute to each anchor that links to an image?

<a href="path/to/image.jpg" data-filetype="image"> Image Link </a>

Then, with that hook in place, we can use a standard attributes selector to target only those anchors.

a[data-filetype="image"] {
   color: red;
}
View Demo

Compatibility

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

16. X[foo~="bar"]

 a[data-info~="external"] {
   color: red;
}

a[data-info~="image"] {
   border: 1px solid black;
}   

Here’s a special one that’ll impress your friends. Not too many people know about this trick. The tilda (~) symbol allows us to target an attribute which has a spaced-separated list of values.

Going along with our custom attribute from number fifteen, above, we could create a data-info attribute, which can receive a space-separated list of anything we need to make note of. In this case, we’ll make note of external links and links to images — just for the example.

"<a href="path/to/image.jpg" data-info="external image"> Click Me, Fool </a>

With that markup in place, now we can target any tags that have either of those values, by using the ~ attributes selector trick.

/* Target data-info attr that contains the value "external" */
a[data-info~="external"] {
   color: red;
}

/* And which contain the value "image" */
a[data-info~="image"] {
  border: 1px solid black;
}

Pretty nifty, ay?

View Demo

Compatibility

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

17. X:checked

input[type=radio]:checked {
   border: 1px solid black;
}   

This pseudo class will only target a user interface element that has been checked - like a radio button, or checkbox. It's as simple as that.

View Demo

Compatibility

  • IE9+
  • Firefox
  • Chrome
  • Safari
  • Opera

18. X:after

The before and after pseudo classes kick butt. Every day, it seems, people are finding new and creative ways to use them effectively. They simply generate content around the selected element.

Many were first introduced to these classes when they encountered the clear-fix hack.

.clearfix:after {
    content: "";
    display: block;
    clear: both;
    visibility: hidden;
    font-size: 0;
    height: 0;
    }

.clearfix { 
   *display: inline-block; 
   _height: 1%;
}

This hack uses the :after pseudo class to append a space after the element, and then clear it. It's an excellent trick to have in your tool bag, particularly in the cases when the overflow: hidden; method isn't possible.

For another creative use of this, refer to my quick tip on creating shadows.

According to the CSS3 Selectors specification, you should technically use the pseudo element syntax of two colons ::. However, to remain compatible, the user-agent will accept a single colon usage as well. In fact, at this point, it's smarter to use the single-colon version in your projects.

Compatibility

  • IE8+
  • Firefox
  • Chrome
  • Safari
  • Opera

19. X:hover

div:hover {
  background: #e3e3e3;
}   

Oh come on. You know this one. The official term for this is user action pseudo class. It sounds confusing, but it really isn't. Want to apply specific styling when a user hovers over an element? This will get the job done!

Keep in mind that older version of Internet Explorer don't respond when the :hover pseudo class is applied to anything other than an anchor tag.

You'll most often use this selector when applying, for example, a border-bottom to anchor tags, when hovered over.

a:hover {
 border-bottom: 1px solid black;
}   

Pro-tip - border-bottom: 1px solid black; looks better than text-decoration: underline;.

Compatibility

  • IE6+ (In IE6, :hover must be applied to an anchor element)
  • Firefox
  • Chrome
  • Safari
  • Opera

20. X:not(selector)

div:not(#container) {
   color: blue;
}   

The negation pseudo class is particularly helpful. Let's say I want to select all divs, except for the one which has an id of container. The snippet above will handle that task perfectly.

Or, if I wanted to select every single element (not advised) except for paragraph tags, we could do:

*:not(p) {
  color: green;
}   
View Demo

Compatibility

  • IE9+
  • Firefox
  • Chrome
  • Safari
  • Opera

21. X::pseudoElement

p::first-line {
   font-weight: bold;
   font-size: 1.2em;
}  

We can use pseudo elements (designated by ::) to style fragments of an element, such as the first line, or the first letter. Keep in mind that these must be applied to block level elements in order to take effect.

A pseudo-element is composed of two colons: ::

Target the First Letter of a Paragraph

p::first-letter {
   float: left;
   font-size: 2em;
   font-weight: bold;
   font-family: cursive;
   padding-right: 2px;
}   

This snippet is an abstraction that will find all paragraphs on the page, and then sub-target only the first letter of that element.

This is most often used to create newspaper-like styling for the first-letter of an article.

Target the First Line of a Paragraph

p::first-line {
   font-weight: bold;
   font-size: 1.2em;
}   

Similarly, the ::first-line pseudo element will, as expected, style the first line of the element only.

"For compatibility with existing style sheets, user agents must also accept the previous one-colon notation for pseudo-elements introduced in CSS levels 1 and 2 (namely, :first-line, :first-letter, :before and :after). This compatibility is not allowed for the new pseudo-elements introduced in this specification." - Source

View Demo

Compatibility

  • IE6+
  • Firefox
  • Chrome
  • Safari
  • Opera

22. X:nth-child(n)

li:nth-child(3) {
   color: red;
}   

Remember the days when we had no way to target specific elements in a stack? The nth-child pseudo class solves that!

Please note that nth-child accepts an integer as a parameter, however, this is not zero-based. If you wish to target the second list item, use li:nth-child(2).

We can even use this to select a variable set of children. For example, we could do li:nth-child(4n) to select every fourth list item.

View Demo

Compatibility

  • IE9+
  • Firefox 3.5+
  • Chrome
  • Safari

23. X:nth-last-child(n)

li:nth-last-child(2) {
   color: red;
}   

What if you had a huge list of items in a ul, and only needed to access, say, the third to the last item? Rather than doing li:nth-child(397), you could instead use the nth-last-child pseudo class.

This technique works almost identically from number sixteen above, however, the difference is that it begins at the end of the collection, and works its way back.

View Demo

Compatibility

  • IE9+
  • Firefox 3.5+
  • Chrome
  • Safari
  • Opera

24. X:nth-of-type(n)

ul:nth-of-type(3) {
   border: 1px solid black;
}   

There will be times when, rather than selecting a child, you instead need to select according to the type of element.

Imagine mark-up that contains five unordered lists. If you wanted to style only the third ul, and didn't have a unique id to hook into, you could use the nth-of-type(n) pseudo class. In the snippet above, only the third ul will have a border around it.

View Demo

Compatibility

  • IE9+
  • Firefox 3.5+
  • Chrome
  • Safari

25. X:nth-last-of-type(n)

ul:nth-last-of-type(3) {
   border: 1px solid black;
}

And yes, to remain consistent, we can also use nth-last-of-type to begin at the end of the selectors list, and work our way back to target the desired element.

Compatibility

  • IE9+
  • Firefox 3.5+
  • Chrome
  • Safari
  • Opera

26. X:first-child

ul li:first-child {
   border-top: none;
}   

This structural pseudo class allows us to target only the first child of the element's parent. You'll often use this to remove borders from the first and last list items.

For example, let's say you have a list of rows, and each one has a border-top and a border-bottom. Well, with that arrangement, the first and last item in that set will look a bit odd.

Many designers apply classes of first and last to compensate for this. Instead, you can use these pseudo classes.

View Demo

Compatibility

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

27. X:last-child

ul > li:last-child {
   color: green;
} 

The opposite of first-child, last-child will target the last item of the element's parent.

Example

Let's build a simple example to demonstrate one possible use of these classes. We'll create a styled list item.

Markup

  <ul>
     <li> List Item </li>
     <li> List Item </li>
     <li> List Item </li>
  </ul>

Nothing special here; just a simple list.

CSS

ul {
 width: 200px;
 background: #292929;
 color: white;
 list-style: none;
 padding-left: 0;
}

li {
 padding: 10px;
 border-bottom: 1px solid black;
 border-top: 1px solid #3c3c3c;
}   

This styling will set a background, remove the browser-default padding on the ul, and apply borders to each li to provide a bit of depth.

Styled List

To add depth to your lists, apply a border-bottom to each li that is a shade or two darker than the li's background color. Next, apply a border-top which is a couple shades lighter.

The only problem, as shown in the image above, is that a border will be applied to the very top and bottom of the unordered list - which looks odd. Let's use the :first-child and :last-child pseudo classes to fix this.

li:first-child {
    border-top: none;
}

li:last-child {
   border-bottom: none;
}   
Fixed

There we go; that fixes it!

View Demo

Compatibility

  • IE9+
  • Firefox
  • Chrome
  • Safari
  • Opera

Yep - IE8 supported :first-child, but not :last-child. Go figure.


28. X:only-child

div p:only-child {
   color: red;
}   

Truthfully, you probably won't find yourself using the only-child pseudo class too often. Nonetheless, it's available, should you need it.

It allows you to target elements which are the only child of its parent. For example, referencing the snippet above, only the paragraph that is the only child of the div will be colored, red.

Let's assume the following markup.

<div><p> My paragraph here. </p></div>

<div>
   <p> Two paragraphs total. </p>
   <p> Two paragraphs total. </p>
</div>

In this case, the second div's paragraphs will not be targeted; only the first div. As soon as you apply more than one child to an element, the only-child pseudo class ceases to take effect.

View Demo

Compatibility

  • IE9+
  • Firefox
  • Chrome
  • Safari
  • Opera

29. X:only-of-type

li:only-of-type {
   font-weight: bold;
}   

This structural pseudo class can be used in some clever ways. It will target elements that do not have any siblings within its parent container. As an example, let's target all uls, which have only a single list item.

First, ask yourself how you would accomplish this task? You could do ul li, but, this would target all list items. The only solution is to use only-of-type.

ul > li:only-of-type {
   font-weight: bold;
}   
View Demo

Compatibility

  • IE9+
  • Firefox 3.5+
  • Chrome
  • Safari
  • Opera

30. X:first-of-type

The first-of-type pseudo class allows you to select the first siblings of its type.

A Test

To better understand this, let's have a test. Copy the following mark-up into your code editor:

<div>
   <p> My paragraph here. </p>
   <ul>
      <li> List Item 1 </li>
      <li> List Item 2 </li>
   </ul>

   <ul>
      <li> List Item 3 </li>
      <li> List Item 4 </li>
   </ul>   
</div>

Now, without reading further, try to figure out how to target only "List Item 2". When you've figured it out (or given up), read on.

Solution 1

There are a variety of ways to solve this test. We'll review a handful of them. Let's begin by using first-of-type.

ul:first-of-type > li:nth-child(2) {
   font-weight: bold;
}  

This snippet essentially says, "find the first unordered list on the page, then find only the immediate children, which are list items. Next, filter that down to only the second list item in that set.

Solution 2

Another option is to use the adjacent selector.

p + ul li:last-child {
   font-weight: bold;
}   

In this scenario, we find the ul that immediately proceeds the p tag, and then find the very last child of the element.

Solution 3

We can be as obnoxious or as playful as we want with these selectors.

ul:first-of-type li:nth-last-child(1) {
   font-weight: bold;   
}   

This time, we grab the first ul on the page, and then find the very first list item, but starting from the bottom! :)

View Demo

Compatibility

  • IE9+
  • Firefox 3.5+
  • Chrome
  • Safari
  • Opera

Conclusion

If you're compensating for older browsers, like Internet Explorer 6, you still need to be careful when using these newer selectors. But, please don't let that deter you from learning these. You'd be doing a huge disservice to yourself. Be sure to refer here for a browser-compatibility list. Alternatively, you can use Dean Edward's excellent IE9.js script to bring support for these selectors to older browsers.

Secondly, when working with JavaScript libraries, like the popular jQuery, always try to use these native CSS3 selectors over the library's custom methods/selectors, when possible. It'll make your code faster, as the selector engine can use the browser's native parsing, rather than its own.

Thanks for reading, and I hope you picked up a trick or two!

Tags: CSScss3
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Sorin

    Very useful, thank you very much.

  • http://www.philohermans.com Philo Hermans

    Great list Jeffrey! :)

  • http://joaomendes.net john

    Great! Thanks

  • Mark

    Jeffrey, Number 2 is prefixing a hash not a pound symbol

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Ahh – old habit. Where I live, refer to the hash symbol as “pound”…like on a phone. But you’re right; I’ll change it.

      • http://heavymark.com Christopher B.

        I’ve always referred to “#” as the pound sign as well. Though I hear people refer to it as a hash when talking about it in the content of twitter or tagging.

      • http://connorcrosby.me Connor Crosby

        Same thing for me, I hear pound, especially on the phone when they give you instructions. I just know hash from Twitter.

    • http://twitter.com/cldx3000 Joern Konopka

      Okay, let me play smart for a minute :P

      I can only transport the different meanings and interpretations of those words by the way i learned about them through translation since i’m not a native english speaker, but this is what i learned. Basically none of you is wrong, if i was loose about the subject i could even refer to the ‘#’ as a MESHTAG. But who does that right? ^^

      # as hash = Would translate to a Collection of Data, a group of the same type, or in the most simple case to a mesh of elements that are related to each other by any commonness, the Pieces of a Pie ( we refer to the Pieces, not the Pie) or Tweets with a certain term [hashtag] like the Cherries on a Pie [they are all fruits/cherries/red]

      # as pound = refers to a certain Unit, a measurable Amount or a certain mass of weight for that matter, it might also refer to a defined area or space ( like a car pound, which refers to the area, not the cars that are on it ), which in the case of CSS delivers a much stronger metaphor than ‘hash’ since it suggests that the referred object is somehow definded by some kind of uniqueness. The Car Pound is in a certain place, it might have a lot of cars, maybe its empty, but there will never be another car pound which is exactly the same since it cannot exist twice in the same time and space.

  • http://laroouse.com esranull

    thanks for tuts very usefull

  • http://www.jamespero.com James Pero

    This one is to the webmaster(s), what are you using to display/format code in the posts? It’s spiffy and I’d like to utilize the same styling for some of my projects…

  • Steven

    Jeffrey you always make things so simple to understand, you make my life so much easier. Thanks

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Thanks, Steven!

  • http://sideroom.com Peepshow

    Awesome. Great summary, this will help a lot.

  • Faust

    Awesome list.
    Some of them are very useful and I didn’t even know them!
    Thx!

  • http://www.igorsbrezinskis.com Igors Brezinskis

    Thanks! Usefull. =)

  • Chris ONeal

    Super-bookmarked. Thank you!

  • http://andrewburgess.ca Andrew Burgess

    Great list, Jeffrey! In #9, you said “It will select . . . any p elements, as long as they are followed by a ul.” I think you mean “as long as they follow a ul”, right?

  • http://www.otadesigns.com/ Hawaii Web Design

    Loved this tutorial! I need to print it asap. I didn’t know many of them. How many don’t work with IE7 though? I know X:last-child doesn’t.

  • http://www.bensmithett.com Ben Smithett

    This is great. If you add browser support details for each selector, this will get a spot in my bookmarks :)

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      I plan to do that this weekend.

      • http://www.bensmithett.com Ben Smithett

        Awesome, looking forward to it!

  • Martin

    Hi. Firstly, let’s just say I love Nettuts. Next, I’d like to say that this article is not of the calibre that I’m used to in nettuts posts.

    It should have never gone to ‘print’ with so many spelling, grammar and other typographical errors. You do have editors, right?

    Secondly, the advice given here is not appropriate in a number of places.

    For example for #X: “id selectors are rigid and don’t allow for re-use. If possible, first try to use one of the new HTML5 elements, or a pseudo-class.”

    That is HORRIBLE advice. ID selectors are VASTLY more effective and efficient than attempting to use an HTML5 element or pseudo-class, which may not even work at all in some older browsers, in either case.

    And, I would like to point out that this is under the “Let’s knock the obvious ones out” section. Um, why would I continue to read after this horrible advice when you’ve already acknowledged that this is the ‘obvious’ section?

    This article reads like it is written like a 13 y/o kid who has just learned HTML/CSS. And, I think it is a great article if that is the case, but in this case, it should be on this kid’s blog, not on nettuts. You have a whole staff there, not just 13 year olds, right?

    I’m definitely looking forward to better content from nettuts.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Hey Martin,

      Firstly, that’s a very rude comment. Secondly, it is far from horrible advice. When you use ids, you can’t reuse the styling within. That’s wasteful. Will it be faster to use an id, rather than a tag name? Fractionally so…yes. But, I’m far more concerned with code reuse. For that matter, let’s just apply ids to everything!

      And, I noted at the beginning of the article that these tips focus on the CSS3 spec, and aren’t cross-browser compatible.

      • http://www.jeffrey-way.com Jeffrey Way
        Author

        Also, in no way am I implying that ids selectors are “bad.” But if I can use the “article” element over “#article”, I will.

      • Martin

        I’m sorry you thought my comments were rude, I only meant them as candid, not hurtful. Nettuts is one of the growing pillars of our industry and I think that it should be held to a standard higher than some 13 yo’s blog. You can accept this as a personal insult if you choose, but I would hope that Nettuts will take it to heart and improve its processes.

        Regarding your #2 above. I try to favour optimizing for the CPU and memory as well as the performance of the experience of the many hundreds, thousands or even millions of my visitors rather than ‘code re-use’. However, with all that left aside, advising that developers us HTML5 tags and pseudo-selectors is simply a bad idea because both of these routes will leave a wide range of older browsers unable to render out site. Sure, this is great if you’re developing for a specific browser, but this is seldom the case and you certainly didn’t specify this limitation in your advice. I still assert that you’ve given bad advice there.

        I have only now noticed that you are the/an editor at nettuts. And, now I understand why you may be less than pleased with my comments. Sadly, I do think that you should have other editors review your work before publishing. This is a good thing for everyone. I know its rather silly to point out everyone’s typos (I’m sure I’ve made some in these comments, but then again, I’m not the editor), but, you should consider using the word ‘preceded’ in #7 and #9, rather than ‘proceeded’ for starters. Also, consistent use of ‘id’ vs. id would be great too. There are more, but its not my job to find and correct these errors, it is the editors.

        I was sincere in saying that I love Nettuts and that I hope to see better content. However, I’m not crazy about one of its editors telling me I’m rude, when I’m only trying to help (albeit in a candid way). I’m sorry if I’ve ruffled your feathers.

      • http://www.jeffrey-way.com Jeffrey Way
        Author

        And I’m not crazy about being compared to a thirteen year old. I’m fairly certain that there’s no other way to interpret this, than as rude.

        Again, in multiple spots, I made reference to the fact that this article refers to the CSS3 spec, and isn’t available in older browsers. In modern browsers, using the HTML5 elements is just fine, and I’ll continue to feel that way. It’s implied that a CSS3 article is not applicable to IE6, without JS intervention. The point of this was to raise awareness of what we *will* be using in the future. Referring to it as “horrible advice” is incorrect and unwarranted. Besides, if you prefer to apply an id to everything, feel free. Many times, it’s necessary, and there’s nothing wrong with doing so.

        Further, the HTML5 elements can absolutely be used in older browsers, just as long as the developer is aware of the fact that the application will then be dependent upon JavaScript to some extent.

        In reference to your “precede” comment – good catch. It’s a simple typo, and a pleasant comment would have been more appropriate than rudeness. I’ve fixed the mistake. I do my best to edit as best as possible, but Nettuts+ is a one-man ship, and not The New York Times. I’m also searching for where I placed “id” in quotes, and I can’t find it.

      • Martin

        “Nettuts+ is a one-man ship”.

        Wow, seriously? Then I am truly very impressed. Keep up the good work.

        Sincerely,
        - Martin

      • http://www.shaneparkerphoto.com Shane Parker

        @Martin

        Do you realize how arrogant and pompous you sound? Even if there were a single good idea in all of your ramblings, I would have written it off due to your completely arrogant and rude tone. It’s ironic that you’d compare Jeffrey’s article to a 13 year old when everything you said could have been said without acting like a 13 year old yourself!

        @Jeffrey

        Great article! It’s always nice to read about how other developers utilize/use code. I use a lot of the same methods that you talked about in the article and even learned some new ones.

    • what?

      who the hell is this guy?…
      a pleasant comment would have been more appropriate than rudeness…
      I agree with you jeff…

    • josh

      Firstly, comparing this article to one written by a 13y/o, is rude. Do it to anyone and I guarantee you’ll get the same response, especially if the article looked nothing like what a 13y/o would write.

      I was also interested in this ID debate. I had a quick look and found this: http://www.thebrightlines.com/2010/07/28/css-performance-who-cares/
      It seems like using other selectors as opposed to ID’s doesn’t make a noticeable difference, so code re-use here is a better option and I fail to see how this is bad advice on Jeff’s part, especially as he stated that it is focused around CSS3. So if you were going to take advantage of CSS3′s capabilities (which aren’t cross compatible with some browsers), then why wouldn’t you take advantage of HTML5 elements too?

      • Martin

        It is bad advice. Sure, there are some scenarios where it may make no difference or may even favor Jeff’s advice, but none of those scenarios are mentioned. And, what does CSS3 have to do with it? The id selector is not CSS3, it is core CSS. Sure, all the way down in the conclusion he says, “If you’re compensating for older browsers, like Internet Explorer 6, you still need to be careful when using these newer selectors” but this is core CSS.

        Now, I have most certainly seen some horribly written code where there are loads of ID’s everywhere (with multiple occurrences of the same ID, etc.), and perhaps Jeff was hoping to stem overuse, but he didn’t say anything about this, he gives blanket, general purpose advice “If possible, first try to use a tag name, one of the new HTML5 elements, or even a pseudo-class.” And, I’ll say it again, this is bad advice.

        All of this discussion is good stuff–and perhaps should have been addressed in the #2 above–but it wasn’t. So, by itself, it is bad advice. I’m sorry.

        Call me rude if you want, but it doesn’t change the fact that it is bad advice for both the performance and non-performance reasons I’ve already stated above here and in previous posts.

        And, let me say, again, that now I know this is a ‘one-man show’, I am sincerely, and without sarcasm, very impressed with Nettuts+ and with Jeff, but that is still bad advice, and what is the worst part is that it is still there, as of this writing.

        Now, let me further say, Jeff has my e-mail address and if he would ever like me to help spot some of these issues before going to ‘print’, I would be more than happy to. Sometimes, a second set of eyes is invaluable and I am volunteering because I think this is a great resource for our community.

        But that advice is still bad.

      • http://net.tutsplus.com Jeffrey Way

        It’s not bad advice. I can show you a dozen different resources that encourage people to use as few id selectors as possible.

        And I note at the very top, and the very bottom of the article that many of the selectors are CSS3. My reference to that comes from the point at which you mentioned that not all browsers can recognize these selectors.

        That section is not going to be removed from the article. Let’s clarify things for everyone: if you can target an element appropriately by doing, for example, article, rather than #article, then feel free to do so. It allows for cleaner, and reusable markup.

        Even without going into specifics, this is not bad advice. It depends 100% on the project at hand. It’s common sense that you should strive to target by tag name first, and then apply ids when you need to be more specific/direct. If your styling can potentially be applied to multiple elements, then allow for that possibility; don’t use an id in that instance.

      • http://www.jeffrey-way.com Jeffrey Way
        Author

        Or, here’s another example: rather than adding a class of “first” to, say, the first list item in a ul, I’d encourage developers to instead use li:first-child.

        Feel free to refer to that as “horribly wrong,” but it’s simply…not.

      • martin

        @Jeff, but you’ve already edited that section when you added ‘tag name’ to the list of alternatives. This helps, thank you.

    • Justin Cribb

      Wow! I bet you’re perfect down to your bones….jeez.

      • http://www.vagrantradio.com Jason

        I disagree with martin completely, aside from not explaining that the * selector is referred to as a universal selector and leaving out grouping selectors (h1, a, li, ul {do:stuff;}) it’s a damn good article.

    • Mike Hopley

      Jeffrey is correct: ID selectors do not allow for effective code reuse. If you use a lot of ID selectors in your CSS, then you’re doing something wrong.

      Code reuse in CSS is important for performance — ironically, given your stance that IDs should be used for performance reasons. The main issue in CSS performance is the size of your CSS file; CSS blocks rendering, so you really want to keep your CSS files small.

      Instead of using IDs all the time, use classes and organise your CSS into modules. Nicole Sullivan explains this in her OOCSS talks. This gets you a large amount of “look and feel” for a small amount of code.

      ID selectors are more useful when selecting DOM elements in javascript. It can be useful to descend from an ID selector, as this is quick to find and reduces the number of DOM elements to be looped through. CSS performance works the opposite way around, however — it’s read “right to left”.

  • dan

    SO useful, thanks!!!

  • http://www.webgrafismo.com Pedro Magalhães

    Absolutely great! BUT you forgot to mention the browser compatibility.
    You know… IE6, IE7 don’t accept all.

    • Eduardo Barros

      What you mean?

      “If you’re compensating for older browsers, like Internet Explorer 6, you still need to be careful when using these newer selectors.”

      • http://www.vagrantradio.com Jason

        He means if you’re hoping to support older browsers like IE6 with these selectors you’re out of luck even if you use Dean Edward’s IE7-JS script http://code.google.com/p/ie7-js/.

        Using JavaScript to fix browser issues isn’t right. It’s an enhancement, not a solution to a problem.

  • http://www.studio0611.de Andreas Papula

    Very nice, useful and comprehensible description of the CSS-Selectors.

    Bookmarked!

    Thx,
    Andi

  • http://contempographicdesign.com Chris Robinson

    Great post Jeffrey, one to bookmark!

  • http://ivorpadilla.net Ivor

    Flexibility to the maximum! Hey Jeff maybe you want to point out that if we use Dean Edward’s IE7-JS script we can still use all this selectors with IE – Download: http://code.google.com/p/ie7-js/ – Selectors supported by the script: http://ie7-js.googlecode.com/svn/test/index.html

    • http://onioneye.com onion eye

      Good one mate :)

      I was surprised to see no one mentioning this, until I saw your comment ;)

      • http://www.jeffrey-way.com Jeffrey Way
        Author

        Yeah, good point. Just added a note to the article. :)

  • http://net.tutsplus.com/tutorials/html-css-techniques/the-30-css-selectors-you-must-memorize/ sandro abuel

    I agree to that you always make thing so easy,
    thank you very much, im learning alot from all of you guys keep up the good work

  • Stu

    Good post Jeffrey thanks!

    @James: It looks to me like they use this Syntax Highlighter: http://code.google.com/p/syntaxhighlighter/wiki/Usage

  • http://www.rafaelfragoso.com Rafael

    Hi Jeffrey, I’m from Brazil and I love your video lessons and tutorials. I bought the premium Nettuts because of its video-lessons, especially because you use Mac OS and even though I am a big fan in Brazil is very expensive, I hope one day to buy it. I’m studying the 2nd year of 2nd degree Technical Computing and doing like a lot of programming and design and this site was helpful, I hope one day owning their knowledge. Very good this tutorial, thanks a lot!

  • Edison Leon

    I will just bookmark this or print it. Thank you!

  • NanoGeek

    Excellent article. I must confess that I learned quite a bit just by skimming through it.

  • http://mixmo-anime.blogspot.com kankuro

    Woooohaaaa!!! my heart is jumping to read this article…. thanks a lot mr. jeff way, for spending a time writing this great, awesome and wonderful article tuts published in this site.. Another knowledge I gain this day upon reading this….

    Thanks a lot for very nice to read…. god bless to you always :D

  • http://prop-14.com Randy

    This is a great article. I really did not know about some of these!

  • http://mixmo-anime.blogspot.com kankuro

    @martin: the capital letter X there represents the types of selector use… just like mathematics let x and let y…. find the value of x and y.

    Now! if you don’t understand what it means then you’re mind is like a 13 y/o kid. Besides if you feel that the article written out above is not worthy, then don’t read it, just find another one….

    As far as i know this article is for the modern browser’s not the old one… sooner or later whether we like it or not…. old browsers will be deprecated.. :D

    P.S thanks for expressing your feelings towards the article :D

    • Martin

      Huh?

  • http://tommasoraspo.com Raspo

    This is nice informative post, but it would be better if you listed some browser compatibility issues with many of these selectors.

    • http://tommasoraspo.com Raspo

      I just noticed that “..many of the selectors mentioned in this article are part of the CSS3 spec, and are, consequently, only available in modern browsers…”

      Sorry, my fault, I always skip the first lines :p

  • http://thatryan.com Ryan

    Jeffrey,

    Fantastic article as always man. I know I am one of many who learn well from your teachings. Some of these I had not even seen before, or knew could be used, so I am looking forward to trying them out.

    Additionally, I see a lot of people mentioning that browser compatibility is not brought up, however in the very introduction paragraph Jeff mentions that,

    “…While many of the selectors mentioned in this article are part of the CSS3 spec, and are, consequently, only available in modern browsers…”

    Anyways, thanks for the knowledge!

    -Ryan

  • http://humachine.us Nik

    This is a great list, but could cause a lot of trouble for someone who missed that sentence in your introduction about cross browser compatibility.

    Including a short summary/overview of compatibility for each selector would make this much more practical for people working on websites today. Each of these has to be cross referenced with a chart to assess what can and can’t be implemented.

    Ivor’s comment rules, though. Thanks.

    Selector/Browser Compatibility Chart:
    http://www.quirksmode.org/css/contents.html

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Yep – valid point. I’ve just added an extra paragraph to the end of the article. Thanks, Nik!

  • http://www.twitter.com/c_t_montgomery Connor Montgomery

    Jeffrey,

    Thank you so much for this article and all of your previous ones. You almost single-handedly taught me about web design and development, and I owe a lot to NetTuts for it. The quality of all the articles is among the best in the field, and the diversity of topics is wonderful, too. Wow, didn’t mean to get off track…

    Anyways, wanted to drop a thank-you and let you know I picked up a few pointers after reading this. Just bookmarked it.

    Best,
    Connor

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Thank you, Connor. That’s nice to hear. :)

      • http://www.mindSmileDesigns.com Jessica

        I just want to second what Connor said. I honestly could’ve written the exact same thing. NetTuts+ has taught me a lot of what I know, and it’s the first place I send people wanting to start learning this field. I wasn’t aware that you do all of this yourself til I read the string of comments up there, and I’m definitely impressed and surprised. With the quality, frequency, and range of content of the articles, I had just always imagined a bunch of developers were behind it. Keep up the good work so I can keep learning how to do good work. =)

  • http://connorcrosby.me Connor Crosby

    Excellent list! I knew some, but a lot I haven’t heard before. Thanks!

  • http://www.greenloungedesigns.com Lyle

    Great article, I really enjoyed the read. It has definately opened more possiblities.

  • Jon Ivee Hernandez

    Nice article. Especially in using the * (Star Symbol) I agree that it will affect the performance if you’re going to declare this one.

  • http://azzcatdesign.com/blog Catherine Azzarello

    Great job, Jeff!

    I’m all for reducing classes and ids when possible–if for no other reason it makes it simpler to style AND edit 6 mos. later. Plus, I’m a ‘disciple’ of CSS-Tricks and Perishable Press.

    I don’t understand all the hullabaloo over ‘compatibility’ w/older browsers *cough* IE *cough*. First, there was Remy Sharp’s HTML5 Shim and now there’s Paul Irish’s & Divya Manian’s HTML5Boilerplate with the Modernizr script.

    So your new elements are covered. And code is cleaner.

    Add in CSS3 PIE and IE is more or less whipped into CSS3 shape.

    Thanks for a great article! Totally bookmarked. :)

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Hey Catherine,

      The hullabaloo only stems from the fact that, at that point, in those older browsers, the layout is dependent upon JavaScript being enabled.

  • http://dtbaker.com.au David

    lol @ comments * face palm *

    I actually didn’t know most of these were valid CSS3 selectors, I had only seen them used in jQuery selectors.

    Very interesting, will definitely implement once CSS3 adoption is more widespread :)

    Regarding point 9: ul ~ p “any p elements, as long as they are followed by a ul”, is it: “any p elements, as long as they follow a ul” or am I confused?

    Top job on the post :) and cannot wait until these can be used on an every day basis.

  • http://dtbaker.com.au David

    Is anyone aware of a jQuery plugin that can parse a CSS document and apply any detected CSS3 styles to the DOM?

    Could be useful to run in a browser that doesn’t support all the above CSS3 tags.

    I’m sure jQuery could understand majority of the above selectors (maybe tweaking a couple).

    Maybe like (very rough broken example):

    step 1) Read CSS data, find any CSS3 tags

    ul ~ p{ color:#FFF; } ul:first-of-type > li:nth-child(2){ font-weight:bold; }

    step 2) Add a style tag to header that contains detected CSS3 tags, slightly modified.

    .css3_tag1{ color:#FFF; } .css3_tag2{ font-weight:bold; }

    step 3) Pass detected CSS3 selectors to jQuery and apply classes to dom:

    $(‘ul:first-of-type > li:nth-child(2)’).addClass(‘css3_tag2′);

    • http://dtbaker.com.au David

      Never mind helps if I Google my idea before posting it lol!

      http://code.google.com/p/ie7-js/

      • http://www.jeffrey-way.com Jeffrey Way
        Author

        Yep – Make sure you use the IE9.js version.

  • http://eraldmariano.com dlare

    …I hope you picked up a trick or two? out of 30, i only knew 6 :mrgreen:

    thanks a lot and a definite +fav!

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Oh good. Yeah – I’m bookmarking it myself, and I wrote it! haha.

  • http://www.diigital.com Mike Healy

    This was a good reminder that I need to brush up on the more powerful selectors. Gotten by with the basic ones for so long. The trick now will be actually remembering and using these.

  • Sahan

    If I want to target a element that has 2 classes I want?

  • guillermo

    I missed the compatibility test, it is VERY important, but anyway awesome list.

  • http://passivetools4u.com Selby

    I always have the most fun with css, its the one thing I can spend hours trying to figure out.

    Thank you for a GREAT reference page.

  • Darren

    Jeffrey, as others have pointed out, #9 is incorrect.

    It says:

    It will select, referring to our example above, any p elements, as long as they are followed by a ul.

    When it should say:

    It will select, referring to our example above, any p elements, as long as they are preceded by a ul.

    • Darren

      Oh, you just fixed it before I refreshed the page.

      By the way, great article.

  • http://www.tutoriallounge.com Tutorial Lounge

    helping tips for web designers for front-end development. thanks

  • Danilux

    This would be really awesome in a cheat sheet, awesome article Jeffrey.

    Hat’s off to you sir for taking some uncall for, rude and unnecesary comments without falling in their game.

  • http://www.ronniesan.com RonnieSan

    Excellent reference post. Coming back from An Event Apart in San Diego, I’ve realized that many front-end developers rely too heavily on classes and IDs. CSS is a very comprehensive language that isn’t taken advantage of often times.

    I’m guilty of using PHP to dynamically add classes like “first” or “last” to elements so i can style them rather than using first-child or last-child. As developers we need to make a strong push towards utilizing newer technologies and relying on graceful degradation to compensate for older browsers.

    A good site to visit is: http://dowebsitesneedtolookexactlythesameineverybrowser.com/

  • Marcus

    This was so… AWESOME!

    Great job Jeff! Especially about the X:nth-child(n) part! Wow I can’t imagine how much I’ve struggled with some CMS’s to include a specific class every third or so of an element.

    This is great and it will save me loads of time. Great friday!

    Cheers man.

  • Deon Smith

    Very nice list. A couple of new toys for me to play with on my next project. This is getting bookmarked for sure.

  • Helen

    “Pro-tip – If your selector looks like X Y Z A B.error, you’re doing it wrong. Always ask yourself if it’s absolutely necessary to apply all of that weight.”

    Jeff, why is it called CASCADING style sheet then?

    Furthermore: If you avoid applying weight on the CSS, and are applying it on the html-markup. X Y Z A B.error means, You have hardly any <pre name="code" <p class="superspan-7764"> Everything is centralised in one single CSS-file. If you want to relaunch your website, you only have to relaunch the CSS. The HTML can remain as it is.