【问题标题】:How to make a scroll div height only as big as sibling div in row [duplicate]如何使滚动div高度仅与行中的兄弟div一样大[重复]
【发布时间】:2020-12-10 07:37:13
【问题描述】:

这可能只使用 css 吗?有两个兄弟元素。第二个元素的高度仅足以容纳其子元素(子元素可能会随着时间而改变)。第一个元素应与第二个元素具有相同的高度。如果它的内容大于它的高度,那么它应该滚动溢出。

下面的 sn-p 与此不匹配,因为第一个元素占据了完全显示其内容所需的高度。

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#container {
  border-style: solid;
  border-width: 1px;
  border-color: #000;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  width: fit-content;
}

#first {
  background-color: #00F;
  overflow-y: scroll;
  height: 100%;
}

#second {
  background-color: #0F0;
  height: fit-content;
  width: 200px;
}

#block {
  height: 40px;
  width: 40px;
  margin: 5px;
  background-color: #F00;
}
<div id="container">
  <div id="first">
    <div id="block">
    </div>
    <div id="block">
    </div>
    <div id="block">
    </div>
  </div>
  <div id="second">
    <div id="block">
    </div>
    <div id="block">
    </div>
  </div>
</div>

【问题讨论】:

    标签: html css


    【解决方案1】:

    您应该用额外的包装器包装#first 并为其应用背景颜色。并在#first 上使用height:0 min-height:100% 技巧

    我还修复了您的 html 错误。一个 ID 每页只能使用一次。所以我把#block改成了.block

    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    
    #container {
      border-style: solid;
      border-width: 1px;
      border-color: #000;
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      width: fit-content;
    }
    
    .scroll-area {
      overflow-y:auto;
      background-color: #00F;
    }
    
    #first {
      min-height: 100%;
      height: 0;
    }
    
    #second {
      background-color: #0F0;
      /* height: fit-content; // unnecessary */
      width: 200px;
    }
    
    .block {
      height: 40px;
      width: 40px;
      margin: 5px;
      background-color: #F00;
    }
    <div id="container">
      <div class="scroll-area">
        <div id="first">
          <div class="block">
          </div>
          <div class="block">
          </div>
          <div class="block">
          </div>
        </div>
      </div>
      <div id="second">
        <div class="block">
        </div>
        <div class="block">
        </div>
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-15
      • 2017-09-12
      • 1970-01-01
      相关资源
      最近更新 更多