HTML and CSS Styling Tables Elements Trick (nth-child)

Taimoor Sattar author Posted on

Creating tables in Html is the combination of tr and th tag. For this blog post, we will be a creating Table in HTML for the grocery store item and styling in CSS. Here are elements of HTML used in table:

  • tr
  • td
  • thead
  • tbody
  • tfoot

tr stand for table row. td stand for table data. thead stand for table head. tbody stand for table footer. To create a row in Table, tr tag is used and to pace data inside the row td tag is used. The top row of table which defines the title of column is enclosed in thead tag.The Html code for the table is display below:

Item Name Quantity Price
Potatoes 51 $1.00
Fruit 22 $2.0
Garlic 18 $2.8
Bananas 16 $5
Onions 40 $3.00
Nuts 20 $5
item 167 $18.8

Code of the above table in HTML is shown below.

[formatc lang="markup"]<table> <thead> <tr> <th class="col-item-name">Item Name</th> <th class="col-quantity">Quantity</th> <th class="col-price">Price</th> </tr> </thead> <tbody> <tr> <td>Potatoes</td> <td>51</td> <td>$1.00</td> </tr> <tr> <td>Fruit</td> <td>22</td> <td>$2.0</td> </tr> <tr> <td>Garlic</td> <td>18</td> <td>$2.8</td> </tr> <tr> <td>Bananas</td> <td>16</td> <td>$5</td> </tr> <tr> <td>Onions</td> <td>40</td> <td>$3.00</td> </tr> <tr> <td>Nuts</td> <td>20</td> <td>$5</td> </tr> </tbody> <tfoot> <td>item</td> <td>167</td> <td>$18.8</td> </tfoot> </table>[/formatc]

Styling of the table makes it more good looking. The task we will be doing there is that we will be color every even row of the table. A little trick we will be using is the use of use of nth-child in styling. Using nth-child pseudo selector we can select each even row of table.

Here is Table CSS code below:

[formatc lang="css"]table{ border-spacing: 0; border-collapse: collapse; width: 50%; margin: 20px auto; } table th,table td{ border: 1px solid black; padding: 10px; vertical-align: top; } .col-item-name{ width: 50%; } .col-quantity,.col-price{ width: 25%; } table th { text-align: left; background-color: #869960; color: #fff; text-shadow: 1px 1px 0 rgba(0, 0, 0, 0.4); } table tbody tr:nth-child(even) td{ background-color: lightgreen; } .ammend-table tfoot{ background-color: lightgrey; }[/formatc]

Final after Styling of Table:

Item Name Quantity Price
Potatoes 51 $1.00
Fruit 22 $2.0
Garlic 18 $2.8
Bananas 16 $5
Onions 40 $3.00
Nuts 20 $5
item 167 $18.8