我正在尝试创建一个渲染的页面布局:
桌子上可能有很多列,我不希望它们挤在一起。相反,我希望表格水平滚动。然而,最终发生的情况是表格扩展了其容器并在主布局上创建了水平滚动。滚动条不会显示在表格本身中。
您可以在此处查看代码和实际问题:
.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;
}
<div class="App">
<div class="Sidebar">Sidebar</div>
<main class="Main">
<div class="TitleBar">
<div>Title</div>
<div>
<button>Create</button>
</div>
</div>
<div class="TableContainer">
<table class="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>
首先将您的桌子设置为
display: block
,然后设置 overflow-x: auto
.Table {
display: block;
overflow-x: auto;
white-space: nowrap;
}
正如您所说,进入响应式视图时,行会挤压在一起。您可以通过为
TD
和 TH
元素指定最小宽度来防止这种情况发生,以免折叠超过限制。
这个方法有效。请参阅下面的片段:
注意:我添加了
td min-width
,这样它们就不会相应地缩小以显示其工作原理。
body {
margin: 0;
}
.App {
display: flex;
flex-direction: row;
width: 100vw;
}
.Sidebar {
display: block;
width: 100px;
background-color: red;
flex-grow: 0;
flex-shrink: 0;
}
.Main {
display: flex;
flex-direction: column;
width: calc(100% - 100px);
background-color: green;
}
.TitleBar {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
width: 100%;
}
.TableContainer {
position: relative;
}
td {
min-width: 500px;
}
.Table {
display: block;
overflow-x: auto;
white-space: nowrap;
}
<div class="App">
<div class="Sidebar">Sidebar</div>
<main class="Main">
<div class="TitleBar">
<div>Title</div>
<div>
<button>Create</button>
</div>
</div>
<div class="TableContainer">
<table class="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>
从
overflow-x: scroll
中删除 .TableContainer
并将 overflow-x: auto
添加到 .main
类并尝试。
解决此问题的一个非常简单的方法是您可以添加表格的最小宽度, 您无法在表格本身中添加滚动条。
.Table {
width: 100%;
table-layout: auto;
min-width:800px;
}