Alternate html table row color

In this Post we will see how to add the alternative row color for html table ,for large tables adding alternative color to the rows makes it looks impressive and also it improves the readability for the end user .

HTML Table


index.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
<table border="1" cellpadding='5'>
  <tr>
    <th>Header 1</th>
    <th>Header 2</th>
    <th>Header 3</th>
    <th>Header 4</th>
    <th>Header 5</th>
  </tr>

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

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

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

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

</table>

</body>
</html>

CSS Styling


In CSS there is selector called pseudoseletor or nth-child selector , this selector helps in selecting the specified child element in a group

The keywords 'even' and 'odd' are just convenient shorthands , but what actual is inside this keyword lets see
General Syntax for nth-child selector

 :nth-child(an+b)

Odd Element
tr:nth-child(odd) = tr:nth-child(2n+1)

:nth-child(2n+1)?

(2 * 0) + 1 = 1 = 1st Element
(2 * 1) + 1 = 3 = 3rd Element
(2 * 2) + 1 = 5 = 5th Element

etc..

Even Element
tr:nth-child(even)=tr:nth-child(2n)

:nth-child(2n)?

2 * 0 = 0th element
2 * 1 = 2nd element
2 * 2 = 4th element

etc..

style.css
th { color: #fff; background-color: #000000; text-align:center; }
td{height:30px}
table { border-collapse: collapse;}

tr:nth-child(odd) { background-color: #ABCCF2 ; }
tr:nth-child(even) { background-color: #ffffff; }


1 comment:

Alternate html table column color - TutorialsBuzz said...

[…] the Previous Post We have seen how to add alternative color for table rows , in this post we look around how to add alternative color for columns in a table […]

Post a Comment