In this example we are going to see how we can define the width of columns in a table HTML so that said width is different in each of the columns we have.
Create a table in HTML
The first thing to define the width of columns in the table HTML is that we are going to need create a table. Table elements in HTML that we are going to use are
table
to define the table,
tr
to define the row and
td
to define the cell.
This way we are going to create our table:
<table>
<tbody>
<tr>
<th>Country</th>
<th>Capital</th>
<th>Surface</th>
<th>Inhabitants</th>
</tr>
<tr>
<td>Spain</td>
<td>Madrid</td>
<td>504,645 km<sup>2</sup></td>
<td>46.6 M</td>
</tr>
</tbody>
</table>
Width of columns in table using CSS
In order to define the width of columns in the table, we have to use CSS language. Specifically, the CSS language will define the width of the columns through the elements,
td
which are what represent the cells.
Thus, within our page, there will be a part that we will put with all the CSS code. This code will go inside the elements
style
.
<style> <!-- CSS code --> </style>
To be able to access the element
td
we will use the selector:
table td { ... }
If we want to access all the cells in the first column, we will use the pseudo element
nth-child
, to which we will pass the value 1.
table td:nth-child(1) {
...
}
If we want to give the width to other columns, we can do so by changing the value we pass as a parameter: 2, 3, 4,…
If we only want to give the width to the first column, we could also use the pseudo element
first-child
.
table td:first-child {
...
}
We only have to use the property
width
to indicate the size we want to give to the column.
In this way we could define the width of each of the columns of the table as follows:
table td:first-child {
width: 100px;
}
table td:nth-child(2) {
width: 100px;
}
table td:nth-child(3) {
width: 200px;
}
table td:last-child {
width: 150px;
}
We have already seen how simple it is to be able to give a width to each of the columns based on the position they occupy within the table.
