CSS

Element Count

This code sample shows a CSS only solution to define different styles for an element based on the total number of elements. This is handy when you have dynamic list content and want to style it differently for a certain number of list items.

li {
    width: 49%;
    display: inline-block;
    text-align: center;
}
/* three items */
li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
    width: 33%;
}
li {
    width: 49%;
    display: inline-block;
    text-align: center;
}
@for $i from 3 through 5 {
    li:first-child:nth-last-child(#{$i}),
    li:first-child:nth-last-child(#{$i}) ~ li {
        width: #{100%/$i}
    }
}

Sass

Sandbox Demo

One or More Elements

Here is another scenario based on the amount of child elements. Suppose you have a dynamic list that contains one or more links and you want to display a longer label when there is only one item in the list.

nav {
    display: flex;
    flex-wrap: wrap;
}
nav a {
    display: block;
    margin-right: 2rem;
}
nav a:last-child {
    margin-right: auto;
}
nav a span.long {
    display: none;
}
nav a span:not(.long) {
    display: block;
}
nav a:only-child span.long {
    display: block;
}
nav a:only-child span:not(.long) {
    display: none;
}
nav {
    display: flex;
    flex-wrap: wrap;

    a {
        display: block;
        margin-right: 2rem;

        &:last-child {
            margin-right: auto;
        }

        span.long {
            display: none;
        }
        span:not(.long) {
            display: block;
        }
    }
    /* show long text when only one link in the nav */
    a:only-child {
        span.long {
            display: block;
        }
        span:not(.long) {
            display: none;
        }
    }
}

Sandbox Demo

comments powered by Disqus