【问题标题】:Prevent element from overflowing container防止元素溢出容器
【发布时间】:2019-03-21 12:21:44
【问题描述】:

我有以下结构,其中.list 中的名称数量(.name)是动态的。我想要实现的是当内容(取决于 .names 的 n 个)长于 .parent 的固定高度时,.children 都适合 .parent(继承高度)。空间不足可以通过 .list 获得滚动条 (overflow:auto) 来解决。

高度继承适用于单个孩子,但是当有两个或更多时我会遇到很大的问题。

JSFIDDLE HERE

HTML

<div id="grandparent">
  <div id="parent">
    <div id="list" class="children">

      <div class="name">john</div>
      <div class="name">mike</div>
      <div class="name">jack</div>
      <div class="name">terry</div>

    </div>

    <div id="footer" class="children">

      <div>footer</div>

    </div>
  </div>
</div>

CSS

body, html {

  margin: 0;
  width: 100%;
  height: 100%;

}

div {

  box-sizing: border-box;

}

#grandparent {

  background-color:yellow;
  display:flex;
  align-items:center;
  width:100%;
  height: 100%;
  flex: 1;

}

.children, .children div {

  padding: 5px;

}

.children {

  max-height: inherit;

}

.children div {

  width: 100%;
  max-height: inherit;

}

#list {

  overflow: auto;
  padding-bottom:0;

}

#footer {

  padding-top:0;

}

.name {

  background-color: green;

}

#footer div {

  background-color: pink;

}

#parent {

  background-color: blue;
  margin: 0 auto;
  max-height: 100px;

}

附:抱歉代码混乱,我只是在测试不同的选项。

【问题讨论】:

  • 不确定是什么问题。我在 Chrome 和 FF 上获得了垂直滚动条。
  • 是的,但是第二个孩子 - 页脚在父级之外(蓝色 div)

标签: html css flexbox height


【解决方案1】:

将此添加到您的代码中:

#parent {
  display: flex;
  flex-direction: column;
}

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

div {
  box-sizing: border-box;
}

#grandparent {
  background-color: yellow;
  display: flex;
  align-items: center;
  width: 100%;
  height: 100%;
  flex: 1;
}

.children,
.children div {
  padding: 5px;
}

.children {
  max-height: inherit;
}

.children div {
  width: 100%;
  max-height: inherit;
}

#list {
  overflow: auto;
  padding-bottom: 0;
}

#footer {
  padding-top: 0;
}

.name {
  background-color: green;
}

#footer div {
  background-color: pink;
}

#parent {
  background-color: blue;
  margin: 0 auto;
  max-height: 100px;
  
  /* new */
  display: flex;
  flex-direction: column;
}
<div id="grandparent">
  <div id="parent">
    <div id="list" class="children">
      <div class="name">john</div>
      <div class="name">mike</div>
      <div class="name">jack</div>
      <div class="name">terry</div>
    </div>
    <div id="footer" class="children">
      <div>footer</div>
    </div>
  </div>
</div>

jsFiddle demo

因为弹性项目默认设置为flex-shrink: 1,它们会减小它们的大小以免溢出容器。

【讨论】:

  • 就在这一刻想通了。谢谢你的帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-13
  • 1970-01-01
  • 1970-01-01
  • 2016-07-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多