CSS溢出:底部绝对定位的相对高度

时间:2016-05-10 14:06:24

标签: css overflow positioning

是的,关于css的另一个恼人的溢出问题......

以下是我的案例:

HTML

<div id="parent">
  <div id="child1">
    Some short content that may take a line or two.
  </div>
  <div id="child2">
    Some short to very long content that may overflow parent div...
  </div>
<div>

CSS

#parent {
  position: absolute;
  height: 100%;
  width: 100px;
}

#child1 {
}
#child2 {
  overflow: auto;
}

正如您所看到的,我希望child2在需要时溢出父div。但由于我不知道child2的确切高度(因为child1可能会有所不同),我无法进行一些绝对定位,因为我已经习惯bottom: 0px和{{} {1}}。

可以使用的一些JSFiddle:https://jsfiddle.net/6r3ojecL/1/

在最坏的情况下,我会使用一些丑陋的JS代码片段,但如果我能再次掌握css,我会很高兴。 :)

谢谢!

2 个答案:

答案 0 :(得分:4)

使用display: flex的解决方案。查看updated fiddle

#parent {
  display: flex;
  position: absolute;
  height: 50%;
  width: 100px;
  border: 1px solid red;
  background-color: red;
  flex-direction: column;
}
#child1 {
  height: 50px;
  background-color: yellow;
}
#child2 {
  flex: 1;
  background-color: green;
  overflow: auto;
}
<div id="parent">
  <div id="child1"></div>
  <div id="child2">
    child 2 content child 2 content child 2 content child 2 content child 2 content child 2 content child 2 content child 2 content child 2 content
  </div>
</div>

答案 1 :(得分:0)

在父级而不是子级上设置溢出(已更新)。

CSS

#parent {
 position: absolute;
 height: 100%; 
 width: 100px; 
 overflow: auto; 
} 
#child1 { } 
#child2 { }
相关问题