CSS Tables

In this chapter we will talk about how to give styles for tables. We can change the color of headings, of rows which we want. Let's see the example.

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      table {
        width: 100%;
        border-collapse: collapse;
      }
      table, th, td {
        border: 1px solid black;
      }
      thead {
        background-color: #1c87c9;
        color: #ffffff;
      }
      th {
        text-align: center;
        height: 50px;
      }
      tbody tr:nth-child(odd) {
        background: #ffffff;
      }
      tbody tr:nth-child(even) {
        background: #f4f4f4;
      }
    </style>
  </head>
  <body>
    <table>
      <thead>
        <tr>
          <th>Heading</th>
          <th>Heading</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Some text</td>
          <td>Some text</td>
        </tr>
        <tr>
          <td>Some text</td>
          <td>Some text</td>
        </tr>
        <tr>
          <td>Some text</td>
          <td>Some text</td>
        </tr>
        <tr>
          <td>Some text</td>
          <td>Some text</td>
        </tr>
      </tbody>
    </table>
  </body>
</html>

Let's explain the above code.

As you see our table has 2 parts: the first is the part where we have written headings, which is our <thead> part and the second part is the <tbody> part where we have written some text. The table has a black borders, for that we use border property. We can use any color we want as well as we can choose the style of borders.

Table color

As you see the <thead> part of our table is blue and wherever we write some text is in white color. For the blue background we use the background-color property and for the white text we use the color property. The other texts we have written with black color.

Collapse Borders

The border-collapse property sets whether the table borders are collapsed into a single border or separated:

Table Width and Height

The table also has width and height properties. As you see we use these properties in our style, we use width property for all table and the height property for the headings . We can use these properties with pixels and percents.

Table Text Alignment

Now about the table text aligment. As you know before we use text aligment property for the text position. In our example as you see, we use text-aligment property for the heading. For that we use the follow "text-align: center", the text can be left and right parts too. If you forget how you must use it, see the chapter before.

Table Padding

To control the space between the border and content in a table, use the padding property on <td> and <th> elements:

td {
  padding: 15px;
}