It's common practice to use CSS to show and hide elements of a responsive web site at various browser widths.

I encountered a slightly different need - limiting the number of elements at different browser sizes.

CSS also makes this possible, with the :nth-of-type pseudo-class.

  • li:nth-of-type(-n+5) selects the first five list elements.
  • li:nth-of-type(n+6) selects the sixth through the last.

To simply the use of this technique, I created a short SCSS mixin:

@mixin limit($count: 1, $display-type: block)
{
    &:nth-of-type(-n+#{$count}) { 
        display: $display-type;
    }
    &:nth-of-type(n+#{$count+1}) { 
        display: none; 
    }
}

Because the styles cascade in my responsive stylesheet, I need to explicitly hide and show the proper elements each time I use this.

I've also included a optional parameter for display type. If the elements you are limiting use a display type of something other than block, say inline-block, you can specify that.

Usage

Featured articles on takitpart are displayed in a grid. I want to limit that grid to a single row on the homepage, but as the available browser width grows, I want to show more elements.

Here's an HTML fragment:

<div class="featured">
    <article>article 1</article>
    <article>article 2</article>
    <article>article 3</article>
</div>

And here's the SCSS stylesheet using the mixin.

// Smaller screen
@media screen and (min-width: 40em) {
    .featured article { 
        // 6 of 12 columns, 50% width.
        @include column(6);
        // Show two articles.
        @include limit(2); 
    }
}
// Larger screen
@media screen and (min-width: 45em) {
    .featured article { 
        // Reduce width:
        // 4 of 12 columns, 33% width.
        @include column(4);
        // Now show three articles.
        @include limit(3); 
    }
}

See it in use on the takitapart home page.

Why not nth-child?

It's best shown with an example. I'll add a non-article element to my featured articles div.

<div class="featured">
    <h2>Featured</h2>
    <article>article 1</article>
    <article>article 2</article>
    <article>article 3</article>
</div>

article:nth-child(2) selects article 1. nth-child selects the nth of all child elements. The h2 is the 1st child element, even though we are not selecting for it.

article:nth-of-type(2) selects article 2. nth-of-type selects the nth selected child element.

nth-of-type makes more sense, at least to me.

March 28 2013.