如何在小屏设备上实现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
相关产品推荐
相关产品推荐

