表格溢出时水平滚动

新手上路,请多包涵

我在容器中有一个基本表。该表将有大约 25 列。我正在尝试在表格溢出时添加一个水平滚动条,但我真的很难过。

现在发生的情况是,表格单元格通过自动调整单元格的高度并保持固定的表格宽度来容纳单元格内容。

对于为什么我的方法无法解决此问题的任何建议,我很感激。

提前谢谢了!

CSS

 .search-table-outter {margin-bottom:30px; }
.search-table{table-layout: fixed; margin:40px auto 0px auto;  overflow-x:scroll; }
.search-table, td, th{border-collapse:collapse; border:1px solid #777;}
th{padding:20px 7px; font-size:15px; color:#444; background:#66C2E0;}
td{padding:5px 10px; height:35px;}
tr:nth-child(even)  {background: #f5f5f5;}
tr:nth-child(odd)   {background: #FFF;}

HTML

 <div class="search-table-outter wrapper">
    <table class="search-table inner">
        <tr>
            <th>Col1</th>
            <th>col2</th>
            <th>col3</th>
            <th>col4</th>
            <th>col5</th>
            <th>col5</th>
        </tr>
        <?php echo $rows; ?>
    </table>
</div>

JS fiddle(注意:如果可能的话,我希望水平滚动条在带有红色边框的容器中):http: //jsfiddle.net/ZXnqM/3/

原文由 AnchovyLegend 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 805
2 个回答

我认为你的 overflow 应该在外容器上。您还可以明确设置列的最小宽度。像这样:

 .search-table-outter { overflow-x: scroll; }
th, td { min-width: 200px; }

小提琴:http: //jsfiddle.net/5WsEt/

原文由 mayabelle 发布,翻译遵循 CC BY-SA 4.0 许可协议

对于那些不能或不想将 --- 包装在 table div 的人的解决方案(例如,如果 HTML 是从 Markdown 生成的)但仍然想要滚动条:

 table {
  display: block;
  max-width: -moz-fit-content;
  max-width: fit-content;
  margin: 0 auto;
  overflow-x: auto;
  white-space: nowrap;
}
 <table>
  <tr>
    <td>Especially on mobile, a table can easily become wider than the viewport.</td>
    <td>Using the right CSS, you can get scrollbars on the table without wrapping it.</td>
  </tr>
</table>

<table>
  <tr>
    <td>A centered table.</td>
  </tr>
</table>

说明: display: block; 使滚动条成为可能。默认情况下(与表格不同),块跨越父元素的整个宽度。这可以通过 max-width: fit-content; 来防止,它允许您仍然使用 margin: 0 auto; 水平居中表格。 white-space: nowrap; 是可选的(但对本演示很有用)。

原文由 Kaspar Etter 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题