0

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.

5
  • specify width in percentages I guess... check if that works for you... Commented Sep 7, 2016 at 14:26
  • Sorry! Horizontal scrollbar of course - will fix original post. Commented Sep 7, 2016 at 14:30
  • @kukkuz - can't imagine any help from percentage Commented Sep 7, 2016 at 14:32
  • is this what you try to do ? jsbin.com/pelimecisa/1/edit?html,css,output Commented Sep 7, 2016 at 14:36
  • @GCyrillus Exactly! Min-width instead of width is the solution, thanks! Commented Sep 7, 2016 at 18:03

2 Answers 2

4

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That's the correct solution - I was not aware about width vs min-width behavior on that situation.
0

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 */
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.