Home > Mobile >  How to apply style for classes
How to apply style for classes

Time:09-16

How to make it so that the first td with the active class is red, and the second one is yellow

table tr td.active { 
   background: red;
}
<div >
   <table>
     <tr>
       <td >1</td>
       <td >2</td>
       <td >3</td>
     </tr>
     <tr>
       <td >4</td>
       <td >5</td>
       <td >6</td>
     </tr>
     <tr>
       <td >7</td>
       <td >8</td>
       <td >9</td>
     </tr>
   </table>
</div>

CodePudding user response:

You will only be able to do it with JS:

//Select the Second active
const element = document.getElementsByClassName('active')[1];
//Apply the yellow color on the second element.
element.style.backgroundColor = 'yellow';

DEMO

//Select the Second active
const element = document.getElementsByClassName('active')[1];
//Apply the yellow color on the second element.
element.style.backgroundColor = 'yellow';
td.active { 
  background: red;
}
<div >
   <table>
     <tr>
       <td >1</td>
       <td >2</td>
       <td >3</td>
     </tr>
     <tr>
       <td >4</td>
       <td >5</td>
       <td >6</td>
     </tr>
     <tr>
       <td >7</td>
       <td >8</td>
       <td >9</td>
     </tr>
   </table>
</div>

CodePudding user response:

You can select the second child with nth-child().

td.active { 
  background: red;
}
td.active:nth-child(2) { 
  background: yellow;
}
<table>
  <tr>
    <td >1</td>
    <td >2</td>
    <td >3</td>
  </tr>
  <tr>
    <td >4</td>
    <td >5</td>
    <td >6</td>
  </tr>
  <tr>
    <td >7</td>
    <td >8</td>
    <td >9</td>
  </tr>
</table>

CodePudding user response:

In pure CSS you may use :has() (but it has limited support) and detect every .active element except the first one.

.active {
  background: red;
}

/* make siblings of the first .active element in yellow, if any */
.active ~ .active,

/* every .active element contained in a row that follows another
   row that contains an active element must be in yellow */
tr:has(.active) ~ tr .active {

   background: yellow;
}
<div >
   <table>
     <tr>
       <td >1</td>
       <td >2</td>
       <td >3</td>
     </tr>
     <tr>
       <td >4</td>
       <td >5</td>
       <td >6</td>
     </tr>
     <tr>
       <td >7</td>
       <td >8</td>
       <td >9</td>
     </tr>
     <tr>
       <td >7</td>
       <td >8</td>
       <td >9</td>
     </tr>
   </table>
</div>

  • Related