Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent a cascade with CSS

Tags:

html

css

Suppose I have the HTML below. Is there any way to prevent the background-color cascading into the inner table? I.E. leaving the HTML exactly as it is and only modifying the CSS class can I achieve this:

enter image description here

.myClass table {
  background-color: red;
}
<body>
  <div class="myClass">
    <table>
      <tr>
        <td>
          <div>
            <table>
              <tr>
                <td>Hello</td>
              </tr>
            </table>
          </div>
        </td>
        <td>World</td>
      </tr>
    </table>
  </div>
</body>
like image 955
Nick Avatar asked Jun 23 '26 12:06

Nick


2 Answers

I created a code snippet for you:

.myClass table td:nth-child(2) {
  background-color: red;
}
<body>
  <div class="myClass">
    <table>
      <tr>
        <td>
          <div>
            <table>
              <tr>
                <td>Hello</td>
              </tr>
            </table>
          </div>
        </td>
        <td>World</td>
      </tr>
    </table>
  </div>
</body>

Basically you tell CSS to make the background of the 2nd TD in the table the red background:

.myClass table td:nth-child(2){
    background-color:red;
}

More info on nth-child() here.

like image 92
patrick Avatar answered Jun 25 '26 22:06

patrick


Use this instead:

.myClass > table { background: red; }

like image 44
Wim Mertens Avatar answered Jun 25 '26 21:06

Wim Mertens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!