【问题标题】:Make position absolute child fit width and height of parent that overflows due to a different child with min-height and min-width由于具有 min-height 和 min-width 的不同子级而使位置绝对子级适合父级的宽度和高度
【发布时间】:2018-11-08 07:20:30
【问题描述】:

https://codepen.io/petermirmo/pen/eQpWXN

html:

<div class="parent">
  <div class="sibling1">
  </div>
  <div class="sibling2">
  </div>
</div>

css:

.parent {
  background-color:red;
  display:inline-block;
  overflow:auto;
  position:relative;
  width:100%;
}
.sibling1{
  min-height: 4000px;
  min-width: 4000px; 
  width: 100%;
}
.sibling2{
  background-color:orange;

  position: absolute;

  top:0; 
  right:0;
  bottom:0;
  left:0;

}

试图使兄弟2 div 适合整个 .parent div 。我试过溢出:覆盖;位置:相对;给.parent。还将 display: table 添加到 .parent 和 display: table-row;给孩子;如果您有任何想法,请告诉我!请看codepen,它会让情况更清楚:)。

【问题讨论】:

    标签: css


    【解决方案1】:

    只需将父级设为inline-block。默认情况下,它是一个块元素,因此它的宽度被限制为它的父宽度并且你有一个溢出。使用inline-block 将使其适合其内容。

    .parent {
      background-color:red;
      position:relative;
      /*overflow:auto; useless as the overflow is now on an upper level*/
      display:inline-block;
    }
    .sibling1{
      min-height: 4000px;
      min-width: 4000px; 
    }
    .sibling2{
      background-color:orange;
    
      position: absolute;
    
      top:0; 
      right:0;
      bottom:0;
      left:0;
      /*useless
      width:100%;
      height: 100%;*/
    }
    <div class="parent">
      <div class="sibling1">
      </div>
      <div class="sibling2">
      </div>
    </div>

    【讨论】:

    • 如果我将宽度 100% 添加到 .parent 这将停止工作。你知道为什么吗?
    • @petermir 100% 表示其父级的 100%,而父级是主体,因此您限制了父级的宽度,它将不再适合其内容。这就像制作元素块元素......这就是为什么解决方案是使用 inline-block 因为内联块的宽度不是 100% 而是内容宽度
    • 感谢您花时间向我解释。这很有道理。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多