Posts tagged with "pseudoclass"
Let’s say we have the following HTML…
That’s not difficult. It’s a
ul (unordered list) which is by default rendered with bullets, although you’ve got full control over how exactly you want it to render. In this case, we have 6 items. Simple. And here’s how it should render in an empty Windows 8 app (with the default dark theme)…
Now what if we wanted every item to be yellow? Go ahead and think about how you’d do it before you look at my answer.
Here it is…
That’s easy enough. Now what if we wanted to give every other item a dark blue background? Well, there are at least four ways I can think of to do that. I’ll include all four.
The following two are equivalent and will highlight every other line starting with the first…
The first rule contains a formula and the second simply contains the word
nth-child is called a pseudo-class because we didn’t have to manually decorate every other
li tag with a class in order to select them. Instead, we use a pseudo-class. Much easier.
nth-child pseudo-class uses a formula that is always of the form:
an+b. Essentially, CSS is going to plug a set of positive integers starting with 0 into the
n in that equation. The result will be a set of integers. CSS will omit the negative and zero values and use the resulting positive integers to determine which items should be matches.
2n-1 formula then would evaluate to an integer set that looked like
[-1,1,3,5,7,9,…]. CSS would then ignore the -1 and apply this style to the 1st, 3rd, and 5th elements. Because highlighting every other row is likely a very common case, CSS defines the odd keyword to simplify matters.
The following two are also equivalent and will highlight every other line starting with the second…
Again, the first is an equation and the second is a keyword. The set of positive integers
[0,1,2,3,4,5,…] would get evaluated in that equation to
[0,2,4,6,8,10,…]. The 0 would be ignored, and the 2nd, 4th, and 6th list items would have the style applied. Here’s the result…
Here are some other, more advanced uses of the
||Every 3rd element|
||Every 10th element|
||The first 7 elements|
||All elements (pointless)|
||All elements starting with the 4th|
||Every other element starting with the 3rd|
So there you have it. That’s nth-child. Pretty handy, eh?
Now let’s look at nth-of-type and see how it differs from nth-child. Consider the following HTML now…
Now we have a
div that has mixed child types. It has some
p elements and some child
When we attempt to apply the same blue style to the second div using our
We don’t get the desired effect. Nothing will be highlighted. See, the
nth-child pseudo-class is indicating that our target element has to be the 2nd child, but it’s not. It’s the second div, but it’s not the second child. To specify that we’re looking for the second div, we use
nth-of-type like this…
And that brings us to the end of the post. If you have any questions or comments, please feel free to leave them below.