I created an HTML table with four columns. I want the third column to have a maximum width of 50px. However, the column width is not being applied as expected.
The table should take up 100% of the width of the container, with a fixed layout. Despite setting max-width: 50px
for the third column, it seems to be ignored.
What might be causing this, and how can I fix it?
Here’s my code:
<html>
<head>
<style>
table {
border-bottom: 1px solid black;
border-right: 1px solid black;
border-collapse: collapse;
table-layout: fixed;
width: 100%;
}
table td, table th {
border-left: 1px solid black;
border-top: 1px solid black;
border-bottom: none;
border-right: none;
}
table td:nth-child(3), table th:nth-child(3) {
max-width: 50px;
word-wrap: break-word;
}
</style>
</head>
<body>
<table>
<thead>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
</thead>
<tbody>
<tr>
<td>88</td>
<td>888888888888</td>
<td>longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong</td>
<td>88888888</td>
</tr>
<tr>
<td>AA</td>
<td>AAAAAAAAAAAA</td>
<td>longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong</td>
<td>AAAAAAAA</td>
</tr>
</tbody>
</table>
</body>
</html>
2
Answers
The max-width property does not work effectively for columns in a table when table-layout is fixed is applied. So for that you have to assign width:50px instead of max-width in table row and table header css
The issue arises because the
table-layout: fixed;
property in your CSS causes the browser to set column widths proportionally based on the table’s width and the content in the columns. Whentable-layout: fixed;
is used, the browser does not dynamically adjust column widths to fit content or respectmax-width
. Instead, column widths are determined by the first row and the specified table width.Solution:
To enforce a maximum width for the third column, you need to:
width
property instead ofmax-width
.table-layout: fixed;
withoverflow: hidden;
andtext-overflow: ellipsis;
to handle overflow.Here’s the updated code:
Changes:
width
instead ofmax-width
:table-layout: fixed;
respects thewidth
property, notmax-width
.overflow: hidden;
: Ensures content that exceeds the column width is clipped.text-overflow: ellipsis;
: Adds ellipsis (...
) for clipped content.white-space: nowrap;
: Prevents text from wrapping into multiple lines.