How to Set the Width of the Table Column
In this tutorial, we’ll show how you can set the width of the HTML table column. For that purpose, you need to use some CSS, particularly the width property.
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 <table> element to 100%. Then, in the HTML part, we distribute the table width among <col> elements by applying the width property via the style attribute. You can also specify these properties directly in 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 setting the width of a 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
<div class="demo mt-1 mb-2.5 not-prose">
<table>
<tr>
<td>20%</td>
<td>50%</td>
<td>30%</td>
</tr>
</table>
</div>
How to expand the last column in the table without expanding the table?
To expand the width of the last column without changing the overall table width, you can assign a larger percentage to the last column. For predictable results across browsers, it’s recommended to use table-layout: fixed on the table and apply the width directly to the <td> or <col> element.
How to expand the last column in the table without expanding the table?
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
table {
width: 100%;
table-layout: fixed;
}
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>