Reputation: 1658
I'm looking for a way to create table with fixed-width cells. When window is too narrow, horizontal scroll bar should appear.
In my example, there are two 400px columns, therefore table should be 800px wide. When screen width is less than 800px, then horizontal scrollbar will appear. That's exact behavior, which I'm looking for: http://jsbin.com/xeniwovole/edit?html,css,output
And now to question: can it be done without specifying table width? In real life, table will have dynamic amount on columns and column widths are responsive. Therefore, it's not reasonable to try to calculate table width as sum of column widths.
Upvotes: 0
Views: 1292
Reputation: 9994
Use min-width
and max-width
rather than width
on the table cells. This will prevent the table from resizing the <td>
to fit the table at 100% width, which is its default behaviour.
#wrap {
overflow-x: auto;
}
table {
table-layout: fixed;
width: auto;
}
td {
background-color: yellow;
min-width: 400px;
max-width: 400px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="wrap">
<table>
<tr>
<td>First</td>
<td>Second</td>
</tr>
</table>
</div>
</body>
</html>
Upvotes: 4
Reputation: 1
try using table-layout: fixed; The horizontal layout only depends on the table's width and the width of the columns, not the contents of the cells
table {
table-layout: fixed;
width: 100%; /* width property required */
}
Upvotes: 0