Flex子项不溢出(崩溃)

时间:2018-08-13 06:28:51

标签: html css css3 flexbox

codepen中,我尝试填充子代的高度,如果子代的高度小于父代的高度,或者如果子代的高度超过父代的高度,则使子代溢出。 但是当我对孩子的身高进行硬编码时,我希望有一个滚动条。但相反,孩子们只是在填充父母。

html,body{
  height:100%;
}
.grand-parent{
  height:100%;
  overflow:auto;
  display:flex;
}
.parent{
  display:flex;
  flex-direction:column;
  min-height:100%;
  width:300px;
}

.child{
  height:1500px;
  width:100%;
  display:flex;
}

.green{
  background:green;
}

.blue{
  background:blue;
}
<div class="grand-parent">
  <div class="parent">
    <div class="child green"></div>
    <div class="child blue"></div>
  </div>
</div>

2 个答案:

答案 0 :(得分:0)

尝试下面的代码。

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

.grand-parent{
  height:100%;
  overflow:auto;
}

.parent{
  display:flex;
  flex-direction:column;
  min-height: 100%;
  background:red;
}

.child{
  height:150px;
  width:100%;
  display:flex;
}

.green{
  background:green;
}

.blue{
  background:blue;
}
<div class="grand-parent">
 <div class="parent">
   <div class="child green"></div>
   <div class="child blue"></div>
 </div>
</div>

您犯的错误是,您在display: flex上添加了.grand-parent,在flex: 1上添加了.parent。这意味着.parent将根据.grand-parent的高度进行调整。所以我从样式中删除了这2个属性

答案 1 :(得分:0)

不要为parent使用flex,而应为min-height: 50%设置child

html,
body {
  height: 100%;
}

.grand-parent {
  height: 100%;
  display: flex;
}

.parent {
  flex-grow: 1;
  overflow: auto;
}

.child {
  height: 1500px;
  width: 100%;
  display: flex;
  min-height: 50%;
}

.green {
  background: green;
}

.blue {
  background: blue;
}
<div class="grand-parent">
  <div class="parent">
    <div class="child green"></div>
    <div class="child blue"></div>
  </div>
</div>

相关问题