Search code examples
htmlcssclassstylesparent-child

select all elements within a parent class


I have two tables, this is just the 2nd. I want to style the 2nd table without affecting the first table. I also do not want to have to id or create classes for each tag. Visual studio seems to understand what I'm telling it to do but its not translating onto the web page. What am I missing?

<style>
    .t2 > tr th td{
                   border: 1px solid white;
               }
    </style>

    <table class="t2">
            <tr>
                <th>Column 1</th>

            </tr>
            <tr>
                <td>Data</td>
                <td>Data</td>

            </tr>


        </table>

Solution

  • .t2 > tbody selects <tbody> elements where the parent is a .t2 class element.

    tbody > tr selects all <tr> elements where the parent is a <tbody> element.

    tr > th selects all <th> elements where the parent is a <tr> element.

    tr > td selects all <td> elements where the parent is a <tr> element.

    Although you have not coded <tbody> explicitly, the browser will add in the <tbody> when displaying it.

    enter image description here

    For more info on CSS selectors, please refer to here.

    <style>
      body {
        background-color: skyblue;
      }
      
      .t2 > tbody > tr > th,
      .t2 > tbody > tr > td {
        border: 1px solid white;
      }
    </style>
    
    <table class="t2">
      <tr>
        <th>Column 1</th>
    
      </tr>
      <tr>
        <td>Data</td>
        <td>Data</td>
    
      </tr>
    
    
    </table>