12

I have a simple table

<tr>
     <td class="first">I am the first</td>
     <td class="second">You are the second</td>
     <td class="third">He is third</td>
     <td class="fourth">Someone else is fourth</td>
     <td class="fifth">That guy is fifht</td>
     <td class="sixth">Who care's about sixth</td>
</tr>

I want to apply css rules on some of classes in td only. I can write something like-

td.first, td.fourth, td.fifth
{
    color:purple;
}

This works. Or i can use classes. I was wondering is there any efficient/ better way to write selectors in such case.

My concern: Is browser, is going to look for all class and then search for td for each comma separation. That means it going to find all three classes and then evaluate tag. Is there any way that browser will find all three classes and then matches the tag other than using a single class.

Jhankar Mahbub
  • 9,746
  • 10
  • 49
  • 52

3 Answers3

23

Addressing Your Concern

You state:

My concern: Is browser, is going to look for all td for each comma separation and find the class match. That means it going to find all td tags three times. If this is true, how can i make browser to search for td tags once and then find class matches.

But that is not how css evaluates, as it goes from right to left. In the case you give:

td.first, td.fourth, td.fifth
{
    color:purple;
}

So it will not search "three times" through td elements. Rather, it will match the .first class in your document (where ever it is), then check to see if it is applied to td element, and if so, match. Then evaluate .fourth, etc. in a similar fashion.

So if your concern is iterations through td elements, then your concern is invalid. Your code is efficient as it is.

Community
  • 1
  • 1
ScottS
  • 71,703
  • 13
  • 126
  • 146
3

For specific properties, you can create separate classes. For example, in your case, you can make a class .color and write like this:

<tr>
     <td class="first color">I am the first</td>
     <td class="second">You are the second</td>
     <td class="third">He is third</td>
     <td class="fourth color">Someone else is fourth</td>
     <td class="fifth color">That guy is fifht</td>
     <td class="sixth">Who care's about sixth</td>
</tr>

.color{color:purple;}
codingrose
  • 15,563
  • 11
  • 39
  • 58
  • I agree class would be faster. Is there any css way to define selectors to find multiple classes under a type of element – Jhankar Mahbub Nov 09 '13 at 16:42
  • Great solution, although I'd try to avoid using the class name "purple" itself... it loses meaning if you decide that they should be a different colour, for example :P – Terry Nov 10 '13 at 01:02
0

You can use the :nth-child property to achieve the same without giving all these different classes to your TDs

i.e:

td:nth-child(1), 
td:nth-child(4), 
td:nth-child(5) {
    color:purple;
}
silicakes
  • 6,364
  • 3
  • 28
  • 39