Look Ahead CSS Selectors
Look Back CSS3 Selectors
With CSS3 it is possible to look back within siblings to check if another element exists before the current one:
- 1
- 2
- 3
- 4
- 5
.blue-item ~ .blue-item {
border: 1px pink solid;
}
The second .blue-item
just became pink.
We can also check if an element directly succeeds another one:
- 1
- 2
- 3
- 4
- 5
.blue-item + .blue-item {
border: 1px pink solid;
}
CSS3 selectors similar to look ahead do not exist right now.
Look Ahead with Existing CSS3 Selectors
The selector nth-last-of-type(x)
actually looks ahead.
- 1
- 2
- 3
- 4
- 5
.blue-item:nth-last-of-type(2) {
border: 1px pink solid;
}
Now the first .blue-item
is pink. Sadly, this only works just because both .blue-item
s are the last children. If we change the order, it won’t work anymore:
- 1
- 2
- 3
- 4
- 5
In this case, ”type” is defined as the element name—li
. However, there are still use cases when this comes in pretty handy:
A Real Life Example
Sometimes you have to know how many elements exist and adopt some measurements. One solution could be to add a .has-3-children
modifier class to the parent element. Sometimes, however, you can’t influence the class names because of third party tools.
Example: A container can consist of 1 to 3 buttons. The buttons should fill the full width.
.buttons button {
/* ... */
float: left;
width: 100%
}
.buttons button:nth-last-of-type(2),
.buttons button:nth-of-type(2) {
width: 50%;
}
.buttons button:nth-last-of-type(3),
.buttons button:nth-of-type(2):nth-last-of-type(2),
.buttons button:nth-of-type(3)
{
width: 33.33333%;
}
Using this, selectors can help to calculate the number of elements.
I hope this helps you in solving future problems. Please note this works in Internet Explorer starting from version 9.0; it works well in all other browsers.