Web4College

CSS tables

The tables represent the simple data in the form of 2-D structure (rows and columns). This tutorial describes how to style a table.

Preview Example
Try it

Now we will follow the steps one by one to build a stylish table.



table

Define the width of the table.

Example
Try it
<style>
table{width:100%;}
</style>

It specifies the width of the table.



table, th, td

We define border for the table, td, and th elements.

Example
Try it
<style>
table, th, td {
 border:1px solid rgba(220,220,220,0.5);
 border-collapse:collapse;
}
</style>

The border property specifies the width, style and color of the border. The border properties are specified for all of the elements that are separated by comma (table, th, td).

The border-collapse property collapses the borders of td, th and table elements.



table th, td

Now we specify padding property for the td and th elements.

Example
Try it
<style>
table td,th{
padding:10px 20px;
}
</style>

padding property specifies the thickness of the area around the text in th, td child elements of the table.


Example
Try it
<style>
table th{
background-color:green;
color:white;
}
</style>

The above property defines the background-color and color of the text in th element.

The table th (parent child) means that properties are applied to the child (th) and not to the parent (table). And if the table,td (parent, child) mean that the properties are applied on both parent (table) and child (td) elements.



table tr:nth-of-type(2n+1)

Example
Try it
<style>
table tr:nth-of-type(2n+1){
background-color:rgba(220,220,220,0.5);
}
</style>

what does :nth-child(2n+1) mean?

Here structural pseudo-classes play the role to design alternate rows. It specifies that these properties are applied to odd number rows only. For example, 2n+1 values for different values of n.

  • n=0, 2(0)+1=1 row

  • n=1, 2(1)+1=3 row

  • n=2, 2(2)+1=5 row

  • n=3, 2(2)+1=7 row

Instead of writting 2n+1, odd may also be used. For example, :nth-child(odd) works in the same way as the :nth-child(2n+1).