How to Set the Width of the Table Column
Solution with the CSS width property
If you want to set the width of the table column, you can use some CSS. You need to use the width property.
In the example below, we set the width of the the <table> element to 100%. Then, in the HTML part, we distribute the table width of 100% among <col> elements having span attributes. But you’re free to decide to specify the properties in HTML, or CSS.
Here, we use the :first-child, :nth-child, and :last-child pseudo-classes on <td> elements and style them with background-color.
Example of the setting the width of the table column:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
table {
width: 100%;
}
td:first-child {
background-color: #32a852;
}
td:nth-child(2) {
background-color: #aaaaaa;
}
td:last-child {
background-color: #5696c7;
}
</style>
</head>
<body>
<table>
<colgroup>
<col span="1" style="width: 20%;">
<col span="1" style="width: 50%;">
<col span="1" style="width: 30%;">
</colgroup>
<tbody>
<tr>
<td>20%</td>
<td>50%</td>
<td>30%</td>
</tr>
</tbody>
</table>
</body>
</html>
Result
20% | 50% | 30% |
How to expand the last column in the table without expanding the table?
To expand the width of the last column in the table without changing the width of the entire table, you can set the width
property of the last column using a percentage value that is larger than the current width.
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
table {
width: 100%;
}
td:first-child {
background-color: #32a852;
}
td:nth-child(2) {
background-color: #aaaaaa;
}
td:last-child {
background-color: #5696c7;
width: 60%; /* set width of last column to 60% */
}
</style>
</head>
<body>
<table>
<colgroup>
<col span="1" />
<col span="1" />
<col span="1" />
</colgroup>
<tbody>
<tr>
<td>A</td>
<td>C</td>
<td>C</td>
</tr>
</tbody>
</table>
</body>
</html>