Jhankar Mahbub
Jhankar Mahbub

Reputation: 9848

css selectors to apply rules to multiple class of similar element

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.

Upvotes: 12

Views: 35835

Answers (3)

codingrose
codingrose

Reputation: 15709

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;}

Upvotes: 3

ScottS
ScottS

Reputation: 72281

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.

Upvotes: 23

silicakes
silicakes

Reputation: 6902

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;
}

Upvotes: 0

Related Questions