Advanced Columns using the :nth-child(N)

I recently developed a site for a client who requested their product listings be displayed similar. I decided to use pseudo-selectors :nth-child(N) and a bit of jQuery to help with IE support. I thought this was a great example of when to use :nth-child(N), so I would like to go over this technique today.

Advanced Columns w/ CSS

View Demo

HTML

As stated above, this layout required that each product column be spit out in one big list. To achieve this  effect, the first list item of every 26 items must be floated to the right.
Advanced Columns w/ CSS - Zigzag Columns

<ul class="prodlist">
    <!--List #1 Large/Float Right-->
    <li><a href="#"><img src="lrg.jpg" alt="" /></a></li>
    <!--List #2~13 Small/Float Left-->
    <li><a href="#"><img src="sm.jpg" alt="" /></a></li>
    ...
    <!--List #14 Large/Float Left-->
    <li><a href="#"><img src="lrg.jpg" alt="" /></a></li>
    <!--List #15~26 Small/Float Left-->
    <li><a href="#"><img src="sm.jpg" alt="" /></a></li>
    ...
    <!--List #27 Large/Float Right-->
    <li><a href="#"><img src="lrg.jpg" alt="" /></a></li>
    <!--List #28~39 Small/Float Left-->
    <li><a href="#"><img src="sm.jpg" alt="" /></a></li>
    ...
</ul>

CSS

Style the columns using a list and take note of the last line of CSS using :nth-child(N). To read further on how the :nth-child(N) works.
:nth-child() CSS Tutorial

ul.prodlist {
margin: 0; padding: 0;
list-style: none;
}
ul.prodlist li {
margin: 10px; padding: 0;
float: left;
}
ul.prodlist li img {float: left;}
ul.prodlist li:nth-child(26n+1) {float: right;}

Browser Support?

Almost all modern browsers support :nth-child(N) except our red headed step child Internet Explorer. To cater for IE, we can write a quick line of jQuery.

jQuery – IE Support

For those who are not familiar with jQuery, do check out their site first and get an overview of how it works. I’ve shared a few tricks that I have picked up along the way, you can check those out as well.

Initial Step – Call the jQuery file

You can choose to download the file from the jQuery site, or you can use this one hosted on Google.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>

Directly after the line where you called your jQuery, start a new <script> tag and start your code by using the $(document).ready event. This allows your jQuery code to run the instant the DOM is ready to be manipulated. All we do now is add a float: right; to the :nth-child(26n+1).

$(document).ready(function() {
$('ul.prodlist li:nth-child(26n 1)').css({'float' : 'right'});
});

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest