Why you should know the new CSS3 selectors?

The new CSS3 specification introduces several innovations in many areas. Exactly for this reason it has been subdivided in various modules, independent between them. The selectors module, which probably is going to be the first to become a recommendation of W3C, is costituted by all selectors of CSS 2.1 specification introduced in previous articles, plus a series of “new entries” of which we are going to provide a quick overview.

There are many good reasons to immediately start becoming familiar with these new selectors, but before listing them, let’s take a look at these novelties brought by CSS3.

At the moment the browsers which completely support all selectors of various CSS specifications are Opera, Safari, Chrome and the 3.5 version of Firefox. With regard to Internet Explorer, the support is limited to the attribute selectors (in the versions 7 and 8), we are going to present.

Attribute Selectors

In addition to those already presented, the CSS3 specification introduces three new typologies of attribute selectors:

  • item[attribute^="value"] => selects an item whose attribute begins with “value”
  • item[attribute$="value"] => selects an item whose attribute ends in “value”
  • item[attribute*="value"] => selects an item whose attribute contains the text “value”

The use is identical to previous selectors, the only thing that changes is the target of the selector.
A simple practical use could be that of visually differentiating the internal links from the external ones. Let’s take an extract from a web page:

<p>
   For more information visit our page <a href="/about">contacts</a>
   or visit the <a href="http://website.international.example.com">international website</a>.
</p>

We might want to insert an icon on the right of each link  to an external website, maybe for informing the user that it will open in a new window or something of that sort. Exploiting the fact that undoubtedly the href attribute of external links starts with “http://” it is possible to write:

a[href^="http://"]{
   padding-right:13px;
   background:#FFF url(external.png) center right no-repeat;
}

Here you can see the final effect, simple and efficient.
In the same way you can insert icons to differentiate the various file types, according to the extension:

a[href$="pdf"]{
   padding-right:13px;
   background:#FFF url(icon_pdf.png) center right no-repeat;
}

a[href$="doc"]{
   padding-right:13px;
   background:#FFF url(icon_doc.png) center right no-repeat;
}

a[href$="mp3"]{
   padding-right:13px;
   background:#FFF url(icon_pdf.png) center right no-repeat;
}

In fact, we have assigned to each type of link a different icon, so that the user knows in advance the type of file they are going to download.

Sibling item selector (item1 ~ item2 )

The functioning of this selector is similar to that of an adjacent item selector ( + ) , only it’s less restrictive. In fact, it selects all the elements which are preceded by another spec item, both children of a single parent item. For example:

h2 ~ h3 {
   margin-left:20px;
}

This rule, thus, selects all the third level titles preceded by a second level title. In the following markup as example:

<body>
   <h2>Example page</h2>
   <ul>
      <h3>A fantastic list</h3>
      <li>An item</li>
      <li>An item</li>
      <li>An item</li>
   </ul>
<h3>The rest of the page</h3>
...
</body>

only the second item <h3> will have an augmented left margin, since it is preceded by an item <h2> and are both children of <body>, while the first <h3> is child of item <ul>

Pseudo-classes :not and :target

The pseudo classes :not(item) and :target are another novelty of CSS3.
The first selects all items different from the specified one. For example the following rule is applied to all items excluding paragraphs:

*:not(p){
   color:yellow;
}

The rule is read as “select all items which are not paragraphs and make them yellow.”
The pseudo-class target, instead, is useful when there are internal links to the page and the objective of the link is to be evidenced somehow. For example, let’s consider the following markup:

<ul>
  <li>
    <a href="#first">First</a>
  </li>
  <li>
    <a href="#second">Second</a>
  </li>
  <li>
    <a href="#third">Third</a>
  </li>
  <li>
    <a href="#fourth">Fourth</a>
  </li>
  <li>
    <a href="#fifth">Fifth</a>
  </li>
</ul>

<p id="first">
   This is the first paragraph
</p>
<p id="second">
   This is the second paragraph
</p>
<p id="third">
   This is the third paragraph
</p>
<p id="fourth">
   This is the fourth paragraph
</p>
<p id="fifth">
   This is the fifth paragraph
</p>

Applying the following CSS:

p:target{background-color:#FF3399;}

the paragraphs that are linked become highlighted with a pink background, like in the example.

Structural pseudo-classes I

These pseudo-classes are one of the sensational innovations, since they allow, with the minimal effort, to select alternate items and apply different styles to them, without having to add classes or ID to the HTML document. For example you might want to alternate the background of the lines of a table, or personalize in a different way every comment of your blog. First of all, let’s discover together which are they:

  • :nth-child(n) => selects the nth child of the item
  • :nth-last-child(n) => selects the nth child, counting from the last
  • :nth-of-type(n) => selects the nth item of the same type
  • :nth-last-of-type(n) => selects the nth item of the same type, counting from the last

You thought you didn’t know Math?

You must have surely noticed that these selectors accept (n) as an argument. This argument can be:

  • a number, thus you can use it to select the third item with :nth-child(3), the fifth with :nth-child(5) and so on;
  • ‘odd’ or ‘even’, to select all odd or even items;
  • the formula ‘an+b’ in which a and b are positive or negative numbers.

This last rule is a little bit more complicated to understand compared to the other two, but enough bear in mind that:

  • a => represents the number of items after which the rule is repeated.
  • b => represents the item from which start counting for the application of the rule.

Let’s give immediately an example:

li:nth-child(odd) /*apply the rule to all odd items <li> */
li:nth-child(6) /*apply the rule on the sixth item <li> */
li:nth-child(4n) /*apply the rule every 4 items <li> counting from the first*/
li:nth-child(4n+2) /*apply the rule every 4 items <li> counting from the second*/

The reasoning made for nth-child is also valid for the other pseudo-classes; in this way we can create “groups” of items to which apply the rules that are repeated, without having to insert manually additional classes.
Let’s analyze a real application of these pseudo-classes. Let’s imagine of having a long list of comments to a blog post. We might want to apply different styles to groups of 5 comments, maybe varying the color of the text:

....
<ol>
   <li>
      <h3>User:</h3>
      <p>
         Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam at dolor tellus, ut
         pellentesque est. Sed quis sapien purus. Cras in lectus vel nisi congue pellentesque
         vel ac nisi. Sed sagittis, justo in venenatis rhoncus, massa odio commodo enim,
         porta mollis lorem sem id tellus. Integer in odio vel felis rutrum eleifend id vest
         tellus. Proin neque arcu, eleifend nec cursus vitae, mollis ac eros. Integer ut nibh
         aliquam leo dignissim pellentesque et nec nunc
      </p>
   </li>
   <li>
      <h3>User:</h3>
      <p>
         Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam at dolor tellus, ut
         pellentesque est. Sed quis sapien purus. Cras in lectus vel nisi congue pellentesque
         vel ac nisi. Sed sagittis, justo in venenatis rhoncus, massa odio commodo enim,
         porta mollis lorem sem id tellus. Integer in odio vel felis rutrum eleifend id vest
         tellus. Proin neque arcu, eleifend nec cursus vitae, mollis ac eros. Integer ut nibh
         aliquam leo dignissim pellentesque et nec nunc
      </p>
   </li>
...
</ol>
...
li:nth-child(5n){color:blue;}
li:nth-child(5n+1){color:red;}
li:nth-child(5n+2){color:yellow;}
li:nth-child(5n+3){color:green;}
li:nth-child(5n+4){color:purple;}

With these rules we can, in groups of 5, differentiate every item of the list, without having to modify our markup under any circumstance. I invite you to try out this example and to bring the necessary modifications, so as to become familiar with these powerful selectors.

Structural pseudo-classes 2

In the specification there are other structural pseudo-classes, which can be obtained from the previous, but given that the items to which they are applied are of everyday use, they have been equally inserted:

  • :root => selects the document root (in HTML, it is always the <html> item)
  • :last-child => selects the last child of the container item (it is the opposite of :first-child)
  • :first-of-type => selects the first item of that type
  • :last-of-type => selects the last element of that type
  • : only-child => selects an item which is the only child of the container item
  • : only-of-type => selects an item which is the only child of the container item of that type
  • :empty => selects an empty item (it should not contain even text)

For example, if I wanted to add after the last item of the previous list the text “The end”, I could write:

li:last-child:after{
    content:"the end";
    text-align:center;
    display:block;
    text-transform:uppercase;
}

This rule can be read as “select last item <li> of each list and add the text ‘the end’ immediately after.

Pseudo-classes for forms

CSS3 also introduces pseudo-classes based on the interaction of the user with the forms:

  • :disabled => is applied to all items of the form which are disabled through the HTML attribute ‘disabled’ and which therefore cannot be selected or clicked.
  • :enabled => is applied to all items of the form which are not disabled.
  • :checked => is applied to all checkboxes or radio buttons which are selected by the user.

By rearranging  the form used for the previous example we will have:

<form action="#" method="post" id="commentform">
   <p>
      <label for="author">Name</label>
      <input type="text" name="author" id="author" size="22" tabindex="1" />
   </p>
   <p>
      <label for="email">Email</label>
      <input type="text" name="email" id="email" size="22" tabindex="2" disabled="disabled" />
   </p>
   <p>
      <label for="url">Website</label>
      <input type="text" name="url" id="url" size="22" tabindex="3" /></p>
   <p>
      <input type="checkbox" name="newsletter" checked="checked" />Subscribe to newsletter
   </p>
   <p>
      <textarea name="comment" id="comment" cols="50" rows="10" tabindex="4"></textarea></p>
   <p>
      <input name="submit" type="submit" id="submit" tabindex="5" value="Send Comment"  />
   </p>
</form>

the text field ‘email’ disabled and in addition a checkbox relative to the newsletter. Applying the following CSS:

input[type=checkbox]:checked{
   border:2px solid green;
   background:#396;
  }
  input:disabled{
   background-color:#F66;
  }

we will have a red background for all disabled items, and all ‘checked’ items will be in green, as you can see here.

Conclusions

In the beginning of this article I placed emphasis on the reasons that should make you use the new CSS3 selectors. If all additional functionalities are not enough to convince you, you should learn these instruments for:

  • rendering your work faster: in fact not having to use hacks and additional filters (even only for selecting the last <li> of a list) the development process will become a lot faster. Thus you can save precious time. And saving time is equal to €€;
  • pushing the browser-vendors to implement the new recommendations: the more developers use these specifications, the more browser manufacturers have to add support in their software. This is translated into less time spent testing on various browsers and programs, rendering the entire development more fluid. The conclusions are the same to those on the previous point;
  • improving the maintenance and the flexibility of your documents: through the use of these selectors, the use of hacks would be remarkably reduced, rendering the modifications to the CSS a lot easier.

Other articles in our guide:

Maybe you are interested for..

Are you using all of the available css selectors?

Master per Web Designer Freelance
In tutti questi anni abbiamo ricevuto centinaia di richieste di approfondimento sulle numerose tematiche del web design vissuto da freelance. Le abbiamo affrontate volta per volta. Ma ci siamo resi conto che era necessario fare qualcosa di più. Ecco perché è nato One Year Together, un vero e proprio master per web designer freelance che apre finalmente le porte al mondo del lavoro.
Scopri One Year Together »
[pdf]Scarica articolo in PDF[/pdf]
Tags:

The Author

Fond of web design, takes delight in creating (X)HTML+CSS layouts. A maniac of polished and tidy codes, the type of person you find in your house straightening the paintings hanging on the wall. He has made his mind of becoming a web designer with a capital “w”, and spends entire nights awake in order to make his dream come true.

Author's web site | Other articles written by

Related Posts

Other articles

Here are some other articles you might find interesting:

    11 comments

    Trackback e pingback

    1. uberVU - social comments
      Social comments and analytics for this post... This post was mentioned on Twitter by mktvitortavares: Why you should know the new …
    2. Why you should know the new CSS3 selectors? | brutally succinct
      [...] Why you should know the new CSS3 selectors? | Your Inspiration Web. Share and Enjoy: [...]
    3. This Week In Web 3 « Keith Cirkel
      [...] Your Inspiration Web talks about why you should know the new CSS3 selector rules - and how to use …
    4. CSS3 Tutorials and Resources - WebsitesMadeRight.com
      [...] Why you should know the new CSS3 selectors? (Your Inspiration Web | Apr 21, 2010) [...]

    Leave a Reply

    Current month ye@r day *