目前,我正在尝试创建一个子表,该子表的宽度可以超过父表的100%。因此,它们应该具有滚动条。但是,当我在下面的CSS中尝试该方法时,子级具有滚动条,并且由于某种原因扩展了父级容器的宽度。如果我使用500px之类的静态尺寸,效果很好,但是宽度为100%时会失败。
(简体)
<main class="main">
<table>
<tr>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
</tr>
</table>
</main>
(简体)
.main {
margin: 0 10%;
padding: 00;
width: 80%;
display: table;
}
table {
margin: 0;
padding: 0;
width: 100%;
display: block;
overflow-x: auto;
white-space: nowrap;
}
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
padding: 0;
width: 100%;
background-color: green;
}
.main {
margin: 0 10%;
padding: 00;
width: 80%;
display: table;
}
table {
margin: 0;
padding: 0;
width: 500px;
display: block;
overflow-x: auto;
white-space: nowrap;
}
</style>
</head>
<body>
<main class="main">
<table>
<tr>
<td>A very very very veeeeeeeeeeeeeeeeeeeeery loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong line</td>
<td>...</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
</tr>
</table>
</main>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
padding: 0;
width: 100%;
background-color: green;
}
.main {
margin: 0 10%;
padding: 00;
width: 80%;
display: table;
}
table {
margin: 0;
padding: 0;
width: 100%; /* PROBLEM */
display: block;
overflow-x: auto;
white-space: nowrap;
}
</style>
</head>
<body>
<main class="main">
<table>
<tr>
<td>A very very very veeeeeeeeeeeeeeeeeeeeery loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong line</td>
<td>...</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
</tr>
</table>
</main>
</body>
</html>
谢谢!
答案 0 :(得分:3)
您需要使用table-layout:fixed;
ref 。自动布局可能会产生意外的结果。
固定表格布局
使用这种(快速)算法,表格的水平布局不取决于单元格的内容;它仅取决于表格的宽度,列的宽度以及边框或单元格的间距。
请注意,无论是否使用width:100%
body {
margin: 0;
padding: 0;
width: 100%;
background-color: green;
}
.main {
margin: 0 10%;
padding: 00;
width: 80%;
display: table;
}
table {
margin: 0;
padding: 0;
display: block;
overflow-x: auto;
white-space: nowrap;
}
<main class="main">
<table>
<tr>
<td>A very very very veeeeeeeeeeeeeeeeeeeeery loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong line</td>
<td>...</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
</tr>
</table>
</main>
<main class="main" style="table-layout: fixed;">
<table>
<tr>
<td>A very very very veeeeeeeeeeeeeeeeeeeeery loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong line</td>
<td>...</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
</tr>
</table>
</main>