February 24, 2012

explain this css please

Question by max4ever

I am developing a css for printing in IE8, since i don’t have advanced css selectors( http://net.tutsplus.com/tutorials/html-css-techniques/the-30-css-selectors-you-must-memorize/ ) i concatenate them like this

I need to modifiy certain columns in a table(e.g. make 8th column red, 9th longer, 10 shorter… ecc)

The question is if i use

td+td+td{ /*instead of td:nth-child(3) on modern browsers*/
 set something...
}

all the td from the 3rd one to the last one have that “set something”

so to fix it i have to do

td+td+td+td{
 unset something
}

So i fixed it, but wondering why it acts like this?

Answer by Starx

+ denotes adjacent selectors.

td+td { } Generally means, if a td is preceded by another td then apply certain rule

One more example:

a + p {} Generally means, if p comes after a then apply certain rule.

So the style sheet you are using

td+td+td will apply the style to every td after the third elements. This might be a little complicated to be clear about. Lets see an example with sets of <td>

<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>

Your rule

td + td + td {
    /* apply something */
}

The above rule will apply to two different sets

  1. First one, adjacent sibling from <td>1</td> to <td>3</td> matches td+td+td

  2. Second one, adjacent sibling from <td>2</td> to <td>4</td> also matches td+td+td

So at the end, all the selectors from <td>3</td> end up getting the style

To cancel this effect, you reset the rule adding fourth selector on the style sheet.
i.e

td + td+ td + td {
  /* cancel the effect
  This will catch <td>-4</td> and apply the reset rule */
}

Hope that explains it.


Further Reading

  1. W3 Org
  2. Good Explanation with examples
  3. One more to fully clarify

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!