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.
<br>
<html>
<head>
<style>
table{
width:100%;
}
table, th, td{
border:1px solid rgba(220,220,220,0.5);
border-collapse:collapse;
}
table td,th{
padding:10px 20px;
}
table th{
background-color:rgb(26,161,242);
color:white;
}
table tr:nth-of-type(2n+1){
background-color:rgba(220,220,220,0.5);
}
@media screen and (max-width:600px){
table td,th{
padding:4px 8px;
font-size:16px;
}
@media screen and (max-width:600px){
table td,th{
padding:2px;
font-size:16px;
}
}
</style>
</head>
<body>
<table>
<tr>
<th>Student</th>
<th>Credit Hours</th>
<th>Obtained Marks</th>
<th>Total Marks</th>
</tr>
<tr>
<td>Madelene</td>
<td>3</td>
<td>630</td>
<td>800</td>
</tr>
<tr>
<td>Farnley</td>
<td>3</td>
<td>619</td>
<td>800</td>
</tr>
<tr>
<td>Maddie</td>
<td>3</td>
<td>659</td>
<td>800</td>
</tr>
<tr>
<td>Bailey</td>
<td>4</td>
<td>594</td>
<td>800</td>
</tr>
<tr>
<td>Ada</td>
<td>4</td>
<td>550</td>
<td>800</td>
</tr>
<tr>
<td>Acley</td>
<td>4</td>
<td>510</td>
<td>800</td>
</tr>
</table>
</body>
</html>
<br>Now we will follow the steps one by one to build a stylish table.
table
Define the width of the table.
<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.
<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.
<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.
<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)
<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).