Updated date:

Code Table in HTML

CyberBotMachines - teaching you how to speed up your programming career!

TL;DR Summary

There are two ways to code table in HTML. First one is using the table element and second one is using div element. (will talk about this one in the next section in more detail).

Using table element you can create simplest table that looks like this:

code table

code table

And the code for this table is provided below:

<style>
  body { background-color: lightgreen; }
  th, td { 
    text-align: center;
    line-height: 40px; 
    border: 1px solid;
    width: 200px;
  }
  table {
    border-spacing: 1px;
  }
</style>

<table>
  <thead> <!-- HEADER ROW -->
    <th>Animal</th> <th>Top Speed</th>
  </thead>

  <tbody>
    <tr> <!-- FIRST ROW -->
      <td>Cheetah</td> <td>75 mph</td>
    </tr>
    <tr> <!-- SECOND ROW -->
      <td>Swordfish</td> <td>60 mph</td>
    </tr>
  </tbody>
</table>

In short that is it.

More Details

When you code the table you can use th elements to define the header. From the image above you can see that it's automatically set to bold text so it's distinguishable from regular table cell.

And you can also easily set different background color for the header cells in CSS.

Another option you have when creating a table is div table.

Basically what you do is define each div as a cell and the table is automatically created.

Let's say we set cell width to 200px. That is good but it's not enough. Every cell will all be in a new line like this:

code table div

code table div

This is because even if you limit the width of the div element, it will still "occupy" the full available width of the parent element.

To fix this default behavior all you have to do is add this simple CSS property - float: left; and every cell will fill all the available space in a single row.

Also to limit the number of cells that fit into a single line (i.e. limit the number of columns) - we will define a wrapper element with the class div-table that has width set to 400px so we can fit exactly 2 cells inside.

And this is the end result - we coded a div table that looks like this:

photo - https://www.cyberbotmachines.com/hubpages-photo-code-table

photo - https://www.cyberbotmachines.com/hubpages-photo-code-table

And here is the full code with which you can code this div table yourself:


<style>
  .div-table {
    width: 400px;
  }
  .div-cell {
    outline: 1px solid;
    text-align: center;
    line-height: 40px;
    width: 200px;
    float: left;
  }
</style>

<div class="div-table">
  <div class="div-cell">Animal</div>
  <div class="div-cell">Top Speed</div>

  <div class="div-cell">Cheetah</div>
  <div class="div-cell">75 mph</div>

  <div class="div-cell">Swordfish</div>
  <div class="div-cell">60 mph</div>
</div>

And this is really all there is when you're trying to code table in HTML using any of the available options:
- using table element
- using div table

Until next time,
Will

Related Articles