0
There are no ways of targeting alternate elements using CSS2 but CSS3 has added comprehensive support allowing you to style odd or even rows or even every 3rd, 4th, 5th or user defined number of rows. There are ways of doing so using javascript or even server side code such as PHP but this CSS3 makes it so much easier and more flexible.


First and Last Element Styling


Once again very easy to pick out the first and last defined elements using CSS3

First Element

li:first-of-type { color: blue; margin-left: 15px; }

Last Element

p:last-of-type { color: green; margin-left: 15px; }

First Two Elements

As a demonstration on how flexible CSS3 selectors can be here is an example of the first two elements being selected:
li:nth-child(-n+2) { color: blue; margin-left: 15px; }

Last Two Elements

Of course the same can be done with the last two elements:
p:nth-last-child(-n+2) { color: red; margin-left: 15px; }
Replacing the number 2 will target whatever desired number of elements at the beginning or end.

Odd or Even Rows

li:nth-child(odd) { color: red; margin-left: 25px; }
li:nth-child(even) { color: green; margin-left: 25px; }
Very simple to select odd rows with CSS3 as you can see above example adding a margin and changing the colour of odd or even list-items.

Every 2nd Row

li:nth-child(2n) { color: yellow; margin-left: 15px; }

Specific Row Styling

It’s just as easy to pick out a specific row, here targeting the 2nd list-item and 5th paragraph elements:
li:nth-of-type(2) { color: blue; margin-left: 15px; }
p:nth-child(5) { color: green; margin-left: 15px; }

All but First and Last Elements

It is also possible to combine the above examples and reverse it so that you can target everything in between the first and last elements. This method is slightly different as it uses multiple, stacked selectors to get the job done:

p:not(:first-of-type):not(:last-of-type) { color: orange; margin-left: 15px; }
This means that it is also possible to select everything but the top two and bottom two elements by combining the :not selector and the :nth-child(-n+2) or :nth-last-child(-n+2) selectors:

p:not(:nth-child(-n+2)):not(:nth-last-child(-n+2)) { color: blue; margin-left: 15px; }

Post a Comment

 
Top