You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在小屏设备上实现Tab按钮横向滚动?

解决Tab按钮小屏横向滚动失效问题

问题根源是你给按钮设置了float: left——这个属性会让元素脱离正常文本流,直接破坏.tab容器的white-space: nowrap效果,导致横向滚动无法生效。

只需要做两处修改就能解决:

  • 删掉按钮的float: left
  • 给按钮加上display: inline-block,让按钮保持同一行排列,同时保留块级元素的样式特性(比如padding、点击区域)

修正后的完整代码:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial;}

/* Style the tab */
.tab {
  overflow: auto;
  white-space: nowrap;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
  background-color: inherit;
  /* 移除float: left */
  display: inline-block; /* 添加该属性 */
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}

</style>
</head>
<body>

<h2>Tabs</h2>
<p>Click on the buttons inside the tabbed menu:</p>

<div class="tab">
  <button class="tablinks" onclick="openCity(event, 'London')">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
  <button class="tablinks" onclick="openCity(event, 'Singapore')">Singapore</button>
  <button class="tablinks" onclick="openCity(event, 'Mumbai')">Mumbai</button>
  <button class="tablinks" onclick="openCity(event, 'Dubai')">Dubai</button>
</div>

   
</body>
</html>

现在在小屏设备上,Tab按钮会横向排列,超出容器宽度时自动出现滚动条。

内容的提问来源于stack exchange,提问作者Mandar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 23:06:27