css - 如何向 HTML5 表格添加滚动条?

标签 css html

我有一个 HTML5 表格,我想在其中添加一个滚动条。我希望表格显示十行,然后用户可以向下滚动以查看其他歌曲。如何添加滚动条?

这是我在 HTML5 中的表格代码:

<table id="my_table" table border="5">
  <tr>
    <th>URL</th>
  </tr>
  <tr>
    <td>http://www.youtube.com/embed/evuSpI2Genw</td>
  </tr>
  <tr>
    <td>http://www.youtube.com/embed/evuSpI2Genw</td>
  </tr>
</table>

这是我的 CSS 代码:

#my_table {
    border-radius: 20px;
    background-color: transparent;
    color: black;
    width: 500px;
    text-align: center;
}

最佳答案

如果您有标题到您的表格列并且您不想滚动这些标题,那么这个解决方案可以帮助您:

此解决方案需要 table 元素内的 theadtbody 标签。

table.tableSection {
    display: table;
    width: 100%;
}
table.tableSection thead, table.tableSection tbody {
    float: left;
    width: 100%;
}
table.tableSection tbody {
    overflow: auto;
    height: 150px;
}
table.tableSection tr {
    width: 100%;
    display: table;
    text-align: left;
}
table.tableSection th, table.tableSection td {
    width: 33%;
}

Working fiddle

With comments

注意:如果您确定垂直滚动条始终存在,则可以使用 css3 calc 属性使 thead 单元格与 tbody 单元格对齐。

table.tableSection thead {
    padding-right:18px;   /* 18px is approx. value of width of scroll bar */
    width: calc(100% - 18px);
}

您可以通过使用 javascript 检测滚动条的存在并应用上述样式来执行相同的操作。

关于css - 如何向 HTML5 表格添加滚动条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17584702/

相关文章:

javascript - 带有卡住标题的 HTML 表格

javascript - Jquery .addClass() 阻止 css 转换

html - ID 属性的属性选择器是否不如 ID 选择器具体?

html - 下拉重叠,图像 slider IE8,Joomla

html - CSS 菜单 - 导航栏在选择子项后拒绝突出显示父项

jquery - 如何将 minus px 添加到我的插件中?

javascript - 在 Wordpress 中随机选择颜色

html - 如何使用javascript在jsx中重复插入特殊字符?

javascript - 如何使用 JavaScript 在其 native 站点上播放/暂停 YouTube 播放器?

javascript - 动态绑定(bind)时未触发音频事件