“Hide/Show” Elements Using :nth-of-type & :target CSS Selectors

content-limit

I was recently working on a project that required that no extra backend code or javascript be added. So I needed a CSS workaround for limiting the number images that were displayed in an unordered list before the user clicked “view all”.

This is the solution I came up with including the psuedo class selectors “:nth-of-type” and “:target”

HTML

CSS

The <ul> has a class of “limit” and an id of “more” (this is so when it is selected, the target address is more user-friendly). The “limit” class selects the 6th list item and beyond and sets their displays to none. When the user clicks the link “Show” it targets the “more” id and our handy-dandy :target selector then sets the all list items to display inline-block. This makes it so the only value you’ll have to change is the “6″. The “less” target does nothing more than divert the page from the “more” id.

Notes

A good thing about this technique is that it allows for variability in dynamic content, it doesn’t depend on any “max-height” trick, so the size of your list items can be whatever. But I will say this technique is not ideal in most cases. If you are trying to limit loads of content you’ll have serious loading concerns.