在设置了最大高度的 div 元素内滚动另一个 div 元素

7

我正在尝试制作一个div,它在具有height: auto and max-height:(heightpx);设置的div内滚动其内容。 我注意到,如果将高度设置为一个值并删除max-height,则可以正常工作。

<div style="height:auto; max-height:200px; background:red;">
<div class="fill">
    <div class="fill">
        <div class="fill">
            <div class="scrolly" style="height: calc(100% - 45px)">
                <div>hello</div>
                <div>hello</div>
                <div>hello</div>
                <div>hello</div>
                <div>hello</div>
                <div>hello</div>
                <div>hello</div>
                <div>hello</div>
                <div>hello</div>
                <div>hello</div>
                <div>hello</div>
                <div>hello</div>
                <div>hello</div>
                <div>hello</div>
            </div>
        </div>
    </div>
</div>

.scrolly {
    overflow-x: hidden;
    overflow-y: scroll;
    position: relative;
}

.fill {
    height: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
}

这里有一个 jsfiddle http://jsfiddle.net/szze6a66/


1
如果您使用编辑器将代码内联放置而不是发布 jsfiddle 链接,那将非常有帮助。您可以通过将代码粘贴到评论框中,将其突出显示,然后单击“代码”(看起来像 {} 的按钮)来添加代码。 - Brad
4个回答

5
你只需要使用overflow-y: auto并设置高度即可。
.scrolly {
    overflow-y: auto;
    position: relative;
    max-height: 200px;
}

1
我很确定他想要流体100%高度,而不是固定的200像素。 - Mick

2

0
您已经错误地将 scrolly 类应用于了错误的 div 上。请从示例中的该 div 中删除它,并将其添加到父 div 上。

谢谢,但在这种情况下,我正在尝试让子div本身滚动而不是父div。例如,如果我将文本框添加为父元素中的第一个元素,我想知道是否仍有一种方法可以使带有“hello”的div滚动。 - fredjones
我不知道除非你对滚动子div应用固定高度,否则你无法实现。 - partypete25

-2

由于主要的 div 具有 max-height:200px,因此您可以将带有 .scrolly 类的标签设置为 max-height: 200px,然后它将滚动而不是溢出容器。

.scrolly {
  overflow-x: hidden;
  overflow-y: scroll;
  position: relative;
  max-height: 200px;
}
.fill {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}
<div style="height:auto; max-height:200px; background:red;">
  <div class="fill">
    <div class="fill">
      <div class="fill">
        <div class="scrolly">
          <div>hello</div>
          <div>hello</div>
          <div>hello</div>
          <div>hello</div>
          <div>hello</div>
          <div>hello</div>
          <div>hello</div>
          <div>hello</div>
          <div>hello</div>
          <div>hello</div>
          <div>hello</div>
          <div>hello</div>
          <div>hello</div>
          <div>hello</div>
        </div>
      </div>
    </div>
  </div>
</div>


我非常确定他想要拥有流体的100%高度,而不是固定的200px。 - Mick

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