Tutorials Tonight
Follow Us

CSS TABLES


Table helps us to present data relations in an effective manner.

Tables created in an HTML document can be styled using CSS table properties.

Example:

Name Age Hobby
John (Author) 32 Learning
Jeany 25 Exploration
Leo 20 Entertainment
Jerry 5 Playing


CSS table style

Using CSS we can set following properties to the table :

  1. border-collapse
  2. cell-spanning
  3. Table Caption
  4. Text align
  5. Background



1.) Border collapse

To create a collapsed border table we need to use CSS property border-collapse.

table, td, th {
    border: 1px solid black ;
    border-collapse: collapse ;
}
▶ Run the code

2).Cell spanning multiple rows or column

Cells of tables span only one row and one column but we can increase their spanning to multiple rows or columns.

For spanning multiple rows or columns we can use the attribute rowspan for multiple row span and colspan for multiple column span.

As we can see in the example below:

<table style="width:100%" border="1">
    <tr>
        <th>Name</th>
        <th colspan="2">Books</th>
    </tr>
    <tr>
        <th rowspan="2">Shakespeare</th>
        <td>King Lear</td>
        <td>Romeo and juliet</td>
    </tr>
    <tr>
        <th>Chetan Bhagat</th>
        <td>3 mistakes of my life</td>
        <td>Half Girlfriend</td>
    </tr>
</table>
▶ Run the code

3.) Table Caption

We can add caption to any table. Caption provide basic information about the table.

For creating a caption to the table <caption> tag is used. This tag must be immediately used after the table tag.

To style caption we create classes and use caption-side property.

<table style="width:100%" border="1">
    <caption style="caption-side:bottom">Books and their authors</caption>
    <tr>
        <th>Name</th>
        <th colspan="2">Books</th>
    </tr>
    <tr>
        <th rowspan="2">Shakespeare</th>
        <td>King Lear</td>
        <td>Romeo and juliet</td>
    </tr>
    <tr>
        <th>Chetan Bhagat</th>
        <td>3 mistakes of my life</td>
    </tr>
</table>
▶ Run the code

4.) Text alignment in table

In the grids of row and column texts can be aligned horizontally and vertically.

To align text horizontally use text-align property.

To align text vertically use vertical-align property.

th{
    text-align:center;
}
tr{
    height:15px;
    vertical-align:bottom;
}
▶ Run the code

5.) Background color in table

Using CSS we can add background color to the table element.In example we have created a zebra effect using nth.child() and background-color property.

tr:nth-child(even){
    background-color:silver;
}
▶ Run the code

Follow Us

Copyright © Tutorials Tonight. All Rights Are Reserved.