Recent Post

Categories

Archives

Cow Computing

10 Feb 7

HTML 5 nth-Child

As we all know, HTML 5 is on its way, and there’s going to be a huge addition to the current syntax. In this post, i shall share with you about the “nth-child” feature. Often, we would like to create a table or list with alternate row color as follow:

// HTML Snippet
<div id="test-area">
  <ul>
    <li>row 1</li>
    <li class="even-row">row 2</li>
    <li>row 3</li>
    <li class="even-row">row 4</li>
    <li>row 5</li>
    <li class="even-row">row 6</li>
    <li>row 7</li>
    <li class="even-row">row 8</li>
    <li>row 9</li>
    <li class="even-row">row 10</li>
  </ul>
</div>
// CSS Snippet
ul {
  list-style: none;
}

// color the even rows
.even-row {
  background-color: #ccc;
}

The above method is okay when you are working with simple rule, but how about if i only want 1, 7, 13, 19…(6n+1)th rows to be highlighted. Then you probably need to write some javascript and do calculation to do it. However, with HTML 5, we got a better yet easier way to accomplish this. We will be using the new property “nth-child”. Let me illustrate by rewriting the example above:

// HTML Snippet
<div id="test-area">
  <ul>
    <li>row 1</li>
    <li>row 2</li>
    <li>row 3</li>
    <li>row 4</li>
    <li>row 5</li>
    <li>row 6</li>
    <li>row 7</li>
    <li>row 8</li>
    <li>row 9</li>
    <li>row 10</li>
  </ul>
</div>
// CSS Snippet
ul {
  list-style: none;
}

// Note that n is a special symbol here
li:nth-child(2n) {
  background-color: #ccc;
}

See the power of nth-child? We now no longer need to label alternate rows, instead, we use the nth-child property. We simply tell nth-child with the calculation (e.g. any integers like “1″, “3″, “5″ or using the special “n” variable for help, like: “2n” representing alternative rows, “5n” representing every fifth rows or even the word “odd” and “even”… you might try to edit the code above to use “even” instead of “2n” to accomplish the same effect.), and it will apply the CSS for you. To learn more, you might try the demo page i made.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Reddit
  • StumbleUpon
  • Twitter

No Comments »

No comments yet.

Leave a comment