DIV水平滚动

8
我有一个固定宽度的 div 里面有几个 HTML 元素。内部元素的宽度之和大于容器的宽度。如何让这些内部元素呈现为行内元素(并显示水平滚动条),而不是在达到父元素宽度后换行?
我可以添加一个包装器,并分配一个最小宽度,但我想要的是如果内容改变,它会自动更改大小的东西。
<div id="container">
    <div class="contents" id="one"></div>
    <div class="contents" id="two"></div>
    <div class="contents" id="three"></div>
    <div class="contents" id="four"></div>
</div>

#container {
    width: 100px;
    background-color: #CCC;
    overflow: auto;
    height: 100px;
}

.contents {
    width: 35px;
    height: 60px;
    float: left;
}
#one {
    background-color:#ABC;
}
#two {
    background-color:#333;
}
#three {
    background-color:#888;
}
#four {
    background-color:#AAA;
}

http://jsfiddle.net/elohr/G5YZ6/2/

Thanks!

3个回答

23

使用 display:inline-block 替代 float:left,并在容器中添加 white-space:nowrap;。如果需要,可以在内容元素中添加 white-space:normal演示


2
谢谢。我尝试了display:inline-block,但是我忘记加上white-space:nowrap。 - user1845791

3

尝试以下操作:

  1. float: left 替换为 display: inline-block;
  2. 对容器使用 white-space: nowrap;

CSS:

#container {
    width: 100px;
    background-color: #CCC;
    overflow: auto;
    height: 100px;
    white-space: nowrap;
}

.contents {
    width: 35px;
    height: 60px;
    display: inline-block;
}

Fiddle:http://jsfiddle.net/praveenscience/G5YZ6/6/


这个链接是一个Fiddle,可以帮助您在浏览器中测试和调试JavaScript、HTML和CSS代码。通过这个工具,您可以更轻松地诊断错误和理解代码的功能。

0
在您的根DIV元素中,您可以始终指定溢出为可滚动:
<div id="container" style="overflow: scroll;">
  <div class="contents" id="one"></div>
  <div class="contents" id="two"></div>
  <div class="contents" id="three"></div>
  <div class="contents" id="four"></div>
</div>

OP已经有了overflow: scroll。而且使用内联样式不是一个好主意。 - Praveen Kumar Purushothaman
2
@Praveen - 我看到溢出设置为自动而不是滚动。所以这有点奇怪!如果你能看到滚动条的话。 - Zeddy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接