Monday, October 10, 2016

AtoZ CSS Quick Tip: How to Use the nth-Child CSS Selector

N is for nth-child

We have many powerful CSS selectors available for finding elements on the page and applying styling to them.

The nth-child pseudo selector is probably the most powerful due to the flexibility of its (an+b) expression for finding patterns of elements. This was discussed in detail in the video screencast all about nth-child.

In this quick tip, we’ll look at when you can use nth-child and when you should use a standard class.

When should I use nth-child?

This is a question I get asked by students quite frequently. The first thing to note is that (unfortunately) it depends on the situation. But I’ll try and provide some good baseline criteria.

Firstly, all the :nth-child like selectors are only supported in IE9 and above (with the exception of :first-child) so the first thing to check is the age of browser your project needs to support.

If you need to support IE8 (firstly, sorry to hear that!) then there’s really only one thing you can do; use classes or use :first-child.

Tip 1: Use :first-child when supporting IE8

Imagine you have a horizontal unordered list of nav links and your design needs to have a border to the right of each item - but not the last item.

Instead of adding the border on the right and needing to remove it from the last one, add the border on the left and remove it from the first one.

[code language="css"]
.site-nav li {
border-left: 2px solid grey;
}
.site-nav li:first-child {
border:0;
}
[/code]

Continue reading %AtoZ CSS Quick Tip: How to Use the nth-Child CSS Selector%


by Guy Routledge via SitePoint

No comments:

Post a Comment