【问题标题】:CSS Overflow: relative height with bottom absolute positionningCSS溢出:底部绝对定位的相对高度
【发布时间】:2016-09-05 13:44:39
【问题描述】:

是的,关于 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: 0pxtop: ???px 那样进行一些绝对定位。

一些 JSFiddle 可以玩:https://jsfiddle.net/6r3ojecL/1/

在最坏的情况下,我会使用一些难看的 JS 代码 sn-p,但如果我能再次掌握 css,我会很高兴。 :)

谢谢!

【问题讨论】:

    标签: css overflow positioning


    【解决方案1】:

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

    CSS

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

    【讨论】:

      【解决方案2】:

      使用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>

      【讨论】:

      • Flexbox 在 IE9 及更低版本中不起作用。不适合生产。
      • 不错!我现在必须了解更多关于 flex 的信息,看起来非常有用。谢谢普加兹。
      • @JoostS 该死的 IE... 自 95 年以来一直是异常的来源! 叹息
      • 显示表格是 flexbox 的跨浏览器替代方案。
      猜你喜欢
      • 2015-03-31
      • 2014-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-05
      • 2011-04-29
      • 2012-12-21
      • 1970-01-01
      相关资源
      最近更新 更多