父级和溢出式的maxHeight:滚动其中一个子级

时间:2016-05-02 12:07:24

标签: css

可以在父级上设置maxHeight,并将一个特定子级(1)占用为可用空间,并且(2)设置overflow-y: scroll那个孩子?

<div style="max-height: 200px">
  <div>Header that I don't want to specify any height on</div>
  <div style="max-height: auto; overflow-y: scroll">
    <div>Item no 1 in long list>
    <div>Item no 2 in long list>
    ...
  </div>
</div>

上面的代码和max-height: auto不起作用。我最接近的是只有一个孩子并将其max-height设置为inherit,如下所示:

<div style="max-height: 200px">
  <div style="max-height: inherit; overflow-y: scroll">
    <div>Item no 1 in long list>
    <div>Item no 2 in long list>
    ...
  </div>
</div>

哪个有效,但如果我有两个孩子而且其中一个有max-height: inherit,则总高度会太高。

2 个答案:

答案 0 :(得分:4)

您可以使用flexbox选项。

<evaluate expression="webFlowUtil.getBean('api.HelloWorld').test()"/>
.container {
  display: flex;
  max-height: 100px;
  flex-direction: column;
  border: 1px solid red;
}
.header {
  background: #eee;
}

.container > div {
  flex: 0 0 auto;
}
.container > div.content {
  flex: 0 1 auto;
  overflow: auto;
}

通过将容器设置为flex显示并为其指定最大高度,子元素将仅使用此max-height。通过将flex-grow设置为1(flex属性中的第二个参数),内容div将占用尽可能多的空间,而标头仅使用所需的空间。

答案 1 :(得分:0)

在父元素上设置height属性,在子元素上设置max-height,如下所示:

<div>
  <div>Header that I don't want to specify any height on</div>
  <div style="height: 200px; background: pink;">
    <div style="max-height: 100%; overflow-y: scroll; background: yellow;">
      <div>Item no 1 in long list</div>
      <div>Item no 2 in long list</div>
    </div>
  </div>
</div>

如果有足够的元素可以跨越,例如在屏幕上200px,子元素将变为可滚动,如下所示:

<div>
  <div>Header that I don't want to specify any height on</div>
  <div style="height: 200px; background: pink;">
    <div style="max-height: 100%; overflow-y: scroll; background: yellow;">
      <div>Item no 1 in long list</div>
      <div>Item no 2 in long list</div>
      <div>Item no 1 in long list</div>
      <div>Item no 2 in long list</div>
      <div>Item no 2 in long list</div>
      <div>Item no 1 in long list</div>
      <div>Item no 2 in long list</div>
      <div>Item no 2 in long list</div>
      <div>Item no 1 in long list</div>
      <div>Item no 2 in long list</div>
      <div>Item no 2 in long list</div>
      <div>Item no 1 in long list</div>
      <div>Item no 2 in long list</div>
    </div>
  </div>
</div>