Racana
Racana

Reputation: 327

Change background color in 2nd and 3rd columns and odd rows

I'm making a table that merges rows in the first column, so when I try to give it some style like background color on odd rows, the first column doesn't work properly,

https://jsfiddle.net/03o910s7/

I'm using

tr:nth-child(even) {
    background-color: #eee;
}
tr:nth-child(odd) {
    background-color: #fff;
}

To make even rows gray but I need to avoid first and last column

All the best!

(Edited)

Upvotes: 0

Views: 4078

Answers (4)

Ashish Patel
Ashish Patel

Reputation: 772

Try this hope help for you.

<style>
tr:nth-child(even) {
    background-color: red;
}
tr:nth-child(odd) {
    background-color: blue;
}
table tr:first-child, table tr:last-child {
    background:none;
}

</style>

Upvotes: 1

Renuka CE
Renuka CE

Reputation: 686

<!DOCTYPE html>
<html>
<head>
<style> 
tr:nth-child(2n+2) {
    background: gray; <!-- even color except first row-->
}
  tr:nth-child(2n+3) {
    background: yellow;   <!-- odd color-->
}
tr:nth-last-child(-n+1) { 
  background-color: white;  <!-- last row color -->
}
</style>
</head>
<body>

<h1>testing</h1>
<table>
  <tbody>
    <tr>
      <td>First line</td>
    </tr>
    <tr>
       <td>Second line</td>
    </tr>
    <tr>
       <td>Third line</td>
    </tr>
    <tr>
       <td>Fourth line</td>
    </tr>
    <tr>
       <td>Fifth line</td>
    </tr>
   <tr>
       <td>Fifth line</td>
    </tr>
   <tr>
       <td>Fifth line</td>
    </tr>
   <tr>
       <td>Fifth line</td>
    </tr>
  </tbody>
</table>


</body>
</html>

Upvotes: 0

Ziv Levy
Ziv Levy

Reputation: 2044

you should add another properties to the first and last rows as follows:

tr:nth-child(even) {
    background-color: red;
}
tr:nth-child(odd) {
    background-color: yellow;
}
tr:first-child {
    background-color: blue;
}
tr:last-child {
    background-color: green;
}

see live example here: http://codepen.io/anon/pen/zrpGvr

Upvotes: 0

Stephen Lane-Walsh
Stephen Lane-Walsh

Reputation: 86

You could use :not(:first-child) to avoid those elements (for td and/or th). See below

tr:nth-child(even) td:not(:first-child),
tr:nth-child(even) td:not(:last-child) {
    background-color: #eee;
}

Upvotes: 0

Related Questions