Monday, February 14, 2011

A really neat css trick

So, you know how sometimes you just need to get to an element of a certain number with your style rules but you cannot use an additional selector? Well there is a way, though not many people seems to know about it.

Pseudo-selector nth-child is the answer. The simpliest way to use it is to feed it with a single number, say

ul li:nth-child(3) {
   display:none;
}

will make a third element of the list disappear, and that is with css only no js whatsoever. But threre is more, say you will feed it with a simple expression like

ul li:nth-child(2n+1) {
  display:none;
}

What will it do? It will hide every element, that has odd number, of the list.

It works like this - n is getting interger values, and the style is applied to the expression result:
(2x0)+1 = 1 //applied to first element
(2x1)+1 = 3 //third element
....
(2x10)+1 = 21
etc

So with a little of basic math it's really easy to get any style pattern you want.

Selector will also work with "odd" or "even" pharses which are self-explainatory, example

ul li:nth-child(odd) {
  display:none;
}

would affect all elements of the list that have odd numbers (as you probably noticed it would give completely equal result as  2n+1 expression).

It's really cool and very easy to use once you get a little into it, there is a downside however, guess what browser claims no support of the feature and, whille works with it, actually produces really weird results, especially when it handles 0? TADAH of course it's IE. Though there are tons of features we had to give up if we are to seriously consider IE a browser :-)
 
I hope this info was of use to you.

No comments:

Post a Comment