HTML Tables

It is very important to have a good understanding of what tables are in HTML. Nowadays, fortunately, we no longer use them as before, but in the past, web pages were built with tables. However, new HTML frameworks, such as Bootstrap or Foundation, or basically any of them, use a structure based on rows and columns, which we will eventually see if we get into a Bootstrap course. But for now, let's focus on tables.

 

1 - What is a table in HTML

As we all know, a table is what it is. Just like in Word, a table is a block that contains rows and columns with their headers, which allows us to organize content into rows and columns. The combination of each row and column makes a cell, and these cells are what contain the data, which could be images, photos, or any type of media like videos or audio.

2 - How to create tables in HTML

To create a table in HTML, we use the <table> tag. This tag will contain all the information of the table.

2.1 - Rows and columns

The main elements of a table are the rows and the columns.

Rows are defined with the opening and closing tags <tr></tr> inside the <table> tag, while each column is marked with the <td>text</td> tag, specifying the content.

But rows and columns aren't the only elements we can use.

<table>
    <tr>
        <td>campo de futbol</td>
        <td>sábado</td>
        <td>50€</td>
    </tr>
    <tr>
        <td>suma total</td>
        <td>Semana</td>
        <td>110€</td>
    </tr>
</table>  

2.2 - Column headers in a table

Commonly, when we create a table, we use the first row to indicate what each column will contain. For this, we use the <th> tag.

This tag is placed in the first row of our table using a <tr>. What the <th> tag does by default is to display the content of each cell in bold.

<table>
    <tr>
        <th>Lugar gasto</th>
        <th>Día</th>
        <th>Precio</th>
    </tr>
    <tr>
        <td>campo de futbol</td>
        <td>sábado</td>
        <td>50€</td>
    </tr>
    <tr>
        <td>suma total</td>
        <td>Semana</td>
        <td>110€</td>
    </tr>
</table>  

2.3 - Table title

When we define a table, even though it's not mandatory, we might want to specify a title for it. For this, we can use the <caption>title</caption> tag, which goes right after the <title> tag.

2.4 - Table structure tags

We can't finish covering tags for tables in HTML without mentioning the main grouping tags. These allow us to separate the content for the header, the body, and the footer of the table.

  1. thead tag in an HTML table
    • Contains the header cells, that is, includes the <tr> that in turn contains the <th>s.
  2. tbody tag in an HTML table
    • Used to group the content of a table, all the rows with content.
  3. tfoot tag in an HTML table
    • Groups the final content of a table. This is perhaps the least common, since not all tables have a footer. For example, we might have it when calculating expenses to add a total at the end.

We should use the three tags mentioned above to create a table properly. If we don’t include them, the browser will still understand the table, but it’s better to use them. For example, Bootstrap, the styling framework I mentioned earlier, doesn't activate its extra table functionalities unless these tags are present.

Another advantage is that if you print a table on paper and it spans several pages, you can have the header and footer on each printed page.

<table>
    <caption>Título</caption>
    <thead>
        <tr>
            <th>Lugar gasto</th>
            <th>Día</th>
            <th>Precio</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>campo de futbol</td>
            <td>sábado</td>
            <td>50€</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td>suma total</td>
            <td>Semana</td>
            <td>110€</td>
        </tr>
    </tfoot>   
</table> 

3 - Table styles in HTML

But a table on its own is nothing without its attributes, which will give it style. As you've probably noticed, the table doesn't really look like a table yet; we just see two columns, and if we didn't know it was a table, we might think it's just tabbed content.

So, let's look at a quick preview of CSS, just something small for now.

3.0 - CSS preview

To do it properly and avoid using outdated elements, we need to create a style for the table. For that we have to use the <style></style> tag and specify within it the elements we're going to style, in this case, the table element.

3.1 - Add border to an HTML table

To add a border to a table, we simply have to use the border attribute and specify the type of border we want, there are many, and here’s a list: none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset|initial|inherit

table{
    border: double;
}

But as you can see, this only adds a border to the outside of the table. If we want all our rows and columns to have borders, we have to state this in the CSS by adding th and td in the style.

table, th, td{
    border: double;
}

Of course, we can change the color by adding the color property and specifying a color in English or a hexadecimal code.

table, th, td{
    border: double;
    border-color: red;
}

3.2 - Collapse borders in HTML tables

We can see that the border looks terrible because it’s doubled. To avoid this, we need to use the border-collapse property, which detects when two borders are together and merges them.

This is a property for the table, so we have to create another style just for the table that contains it.

table{
    border-collapse: collapse;
}

3.3 - Size of an HTML table

As you can see, the table is as compact as possible, and that's a feature we rarely want. Usually, we want the table to be as wide as the page. Remember that when we create a website, it's rare that the main content takes up the whole screen, so the result would be similar to inserting a table in Word.

To do this, we add the width attribute to the table and set it to 100% if we want it to take up the whole page width.

table{
    border-collapse: collapse;
    width: 100%;
}

As you can see, the change is evident. Also, by default, <th> elements are centered, while normal table cells are left-aligned.

Of course, we can increase the size of the header for better visibility. To do this, we can increase the height using the height property, but in this case, we'll apply it only to the <th> tag in pixels.

th{
    height: 30px;
}

3.4 - Cell spacing

It's obvious at a glance that the content of the cells is very close together, and the text is too near the border. To avoid this, we use a property called padding, which we set with a value, usually in pixels.

td{
    padding: 5px;
}

If you look at the result, there's spacing added in all directions. You can customize which padding you want (top, right, left, or bottom) with padding-top for the top, padding-right for the right, padding-left for the left, and padding-bottom for the bottom.

We can modify all four paddings with a single padding instruction if we pass all four values, which we'll cover in the CSS section.

3.5 - Highlight table rows on hover

One of the most common features when working with tables is highlighting the row you're on. To do this, we use CSS and pseudo-elements, which we'll see later, indicated with the ":" character; "hover" is used when the mouse is over something. In this case, apply it to the <tr> element and change the background color to gray.

tbody > tr:hover{
    background-color: black;
    color: white;
}

3.6 - Alternate row highlighting in HTML tables

Finally, in this section, we’ll see how to drastically improve the look of a table on your website. The best way to do it is also with CSS, using the following selector.

tr:nth-child(odd){
    background-color: #f2f2f2;
}

As you can see, it's a bit strange, as it uses the <tr> selector with a pseudo-element for children nth-child(), to which you pass as a parameter "even" or "odd". Then you open and close the braces.

4 - Nested tables

We can also insert a table inside a cell of another table, which will nest one table within another.

5 - Merge cells

5.1 - Merge columns in HTML tables

Commonly, when creating tables, we want to merge certain columns. A simple example, still with the expenses example, at the end, we’d want to see how much we've spent in total, and display it in an accumulated and visually appealing way.

To do this, we'll group the columns in the last row, leaving just two cells: one for the text indicating it's the sum, and one for the value. For this, we use the colspan attribute on the cell we want to merge and specify how many cells to merge together.

<tfoot>
    <tr>
        <td colspan="2">suma total</td>
        <td>110€</td>
      </tr>
</tfoot>

Be careful not to merge more cells and then not include as many cells as the table has, or your table will expand.

5.2 - Merge rows in HTML tables

We can do the same to combine two rows.

Let’s continue with our example, but this time we'll use rowspan to indicate that we're merging rows.

<tr>
  <td rowspan="2">Cine</td>
  <td>Martes</td>
  <td>10€</td>
</tr>
<tr>
  <td>Miercoles</td>
  <td>10€</td>
</tr>
This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

Uso del bloqueador de anuncios adblock

Hola!

Primero de todo bienvenido a la web de NetMentor donde podrás aprender programación en C# y .NET desde un nivel de principiante hasta más avanzado.


Yo entiendo que utilices un bloqueador de anuncios como AdBlock, Ublock o el propio navegador Brave. Pero te tengo que pedir por favor que desactives el bloqueador para esta web.


Intento personalmente no poner mucha publicidad, la justa para pagar el servidor y por supuesto que no sea intrusiva; Si pese a ello piensas que es intrusiva siempre me puedes escribir por privado o por Twitter a @NetMentorTW.


Si ya lo has desactivado, por favor recarga la página.


Un saludo y muchas gracias por tu colaboración

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café