Max
Max

Reputation: 1501

do not apply css style to child elements

we have

<div class="xTable">
 <table>
  <tr>
   <td>
    <div class="xTable">
     <table>
      <tr>
       <td>
        <div class="xTable">
         <table>...</table>
        </div>
       </td>
      </tr>
     </table>    
    </div>
   </td>
  </tr>
 </table>
</div>

How do I apply custom css styles to 2nd div, only to 2nd div and not to 1 or 3 or deeper?

NO WAY TO ADD EXTRA CLASSES or IDS! Html is generated dynamically and is unmanageable.

I would use

.xTable table .xTable

but that means 3rd and deeper divs will be affected.

no IDs! Please CSS selectors only.

Thanks!

Upvotes: 6

Views: 14357

Answers (7)

James Donnelly
James Donnelly

Reputation: 128791

To cater fully for both this default markup and browsers which correctly add a tbody where it isn't already specified you'd need to use:

body > .xTable > table > tr > td > .xTable,
body > .xTable > table > tbody > tr > td > .xTable {
    ...
}

JSFiddle example.

This assumes that your first <div class="xTable"> has no parents other than <body>. If this isn't the case then replace body with your parent.

Upvotes: 6

Mr_Green
Mr_Green

Reputation: 41832

As you are saying that you can't add class name as provided by @Rob, then I think there is only one way to go with javascript or jquery. Below I provided solution using jQuery.

$('.xTable:eq(1)').css('backgroundColor','green'); //Selects the second .xTable class div

Check more about it here

Upvotes: 1

Michael
Michael

Reputation: 7092

Then could this not be just:

body > .xTable table tr td.xTable {STYLES}

????

Upvotes: 1

Quentin
Quentin

Reputation: 943571

Using a :not selector to exclude the parent and then having a long list of child combinators might do the job:

:not(table) > .xTable > table > tr > td > .xTable

You might need to mix in the implicit tbody elements to that though.

A nicer solution would probably be:

.xTable .xTable {
    foo: bar;
}

.xTable .xTable .xTable {
    foo: Whatever it would have been if the previous selector didn't match
}

Upvotes: 2

Shuping
Shuping

Reputation: 5458

Class composition is recommended. for example <div class="table level-2" />

Upvotes: 0

Sheric
Sheric

Reputation: 416

When you use someelement someotherelement it is not important how much deep you go in the first element. But you can add a > between them to select only the someotherelement that is exactly the child of someelement like this: someelement > someotherelement and it will not select childs of childs of the first selector.

Upvotes: 0

Rob
Rob

Reputation: 4947

I would probably just give the 2nd div an extra css class.

<div class="xTable second-xTable-div"></div>

Upvotes: 2

Related Questions