Home > Software engineering >  How can I stop a table from expanding beyond the size of its container div and scroll instead?
How can I stop a table from expanding beyond the size of its container div and scroll instead?

Time:10-31

I am trying to create a page layout where I render:

  • A fixed width side bar
  • A main content section with
    • A header row (title button)
    • A table

The table may hold quite a few columns and I don't want them to get squished together. Instead, I would like the table to scroll horizontally. However, what ends up happening is that the table expands its container and creates a horizontal scroll on the main layout. The scrollbar doesn't show up in the table itself.

You can see the code and the problem in action here:

HTML

<div >
  <div >Sidebar</div>
  <main >
    <div >
      <div>Title</div>
      <div>
        <button>Create</button>
      </div>
    </div>
    <div >
      <table >
        <thead>
          <tr>
            <th>Name</th>
            <th>Prop 1</th>
            <th>Prop 2</th>
            <th>Prop 3</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>Item 1</td>
            <td>Value 1.a</td>
            <td>Value 1.b</td>
            <td>Value 1.c</td>
            <td>
              <button>Edit</button>
            </td>
          </tr>
          <tr>
            <td>Item 2</td>
            <td>Value 2.a</td>
            <td>Value 2.b</td>
            <td>Value 2.c</td>
            <td>
              <button>Edit</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </main>
</div>

CSS

.App {
  display: flex;
  flex-direction: row;
  width: 100%;
}

.Sidebar {
  display: block;
  width: 150px;
  background-color: red;
  flex-grow: 0;
  flex-shrink: 0;
  flex-basis: 150px;
}

.Main {
  display: flex;
  flex-direction: column;
  width: 100%;
  background-color: green;
}

.TitleBar {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.TableContainer {
  width: 100%;
  position: relative;
  overflow-x: scroll;
}

.Table {
  width: 100%;
  table-layout: auto;
}

Help much appreciated, thanks!

CodePudding user response:

Remove overflow-x: scroll from .TableContainer and add overflow-x: auto to .main class and try.

CodePudding user response:

One very simple way to fix this is you can add minimum width of table.

.Table {
  width: 100%;
  table-layout: auto;
  min-width:800px;
}
  • Related