【问题标题】:Force an element to be 100% height when the parent is shimmed taller by another child [duplicate]当父元素被另一个子元素填充得更高时,强制元素为 100% 高度 [重复]
【发布时间】:2018-04-26 20:14:30
【问题描述】:

这里我有一个包含两个孩子的父 div。子 1 设置为 100% 高度,但它不会显示在父的实际高度,因为子 2 正在强制父 div 更高。

<div style="height: 50px; width:106px">
  <div style="border: 1px solid red; display: flex">
    &nbsp;
    <span style="border: 1px solid blue; height: 100%;">Child 1</span>
    &nbsp;
    <span style="border: 1px solid green; height: 100px;">Child 2</span>
    &nbsp;
  </div>
</div>

在这种情况下,如何让子 1 匹配父 div 的 实际 高度?我想用纯 HTML/CSS 做到这一点。

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    Another answer to this question的解法是正确的,但解释不正确。

    你有一个弹性容器。

    容器有两个 span 孩子:span1 和 span2。

    span1 设置为height: 100%

    span2 设置为height: 100px

    因为 span1 设置为 height: 100% 并且 flex 容器没有定义高度,所以该元素计算为 height: auto(内容的高度)。

    以下是对其工作原理的更完整说明:

    然而,弹性容器的默认设置是align-items: stretch。这意味着弹性项目将扩展以覆盖容器cross axis 的长度,在这种情况下就是高度。

    但是这个默认设置被弹性项目上的height 属性覆盖。

    因此,删除height: 100% 以便align-items: stretch 可以工作。

    现在你有两个等高的列。

    <div style="height: 50px;">
      <div style="border: 1px solid red; display: inline-flex; padding: 5px;">
        <span style="border: 1px solid blue;">Child 1</span>
        <span style="border: 1px solid green; height: 100px; margin-left: 5px;">Child 2</span>
      </div>
    </div>

    【讨论】:

      【解决方案2】:

      您的问题是因为您的 child1 是从父级继承的。如果您将其设置为 100%,则意味着您的孩子 1 的大小将为 50px。让它自动删除你的孩子 1 height: 100%; 下面是一个示例。

      <div style="height: 50px; width:106px">
        <div style="border: 1px solid red; display: flex">
          &nbsp;
          <span style="border: 1px solid blue;">Child 1</span>
          &nbsp;
          <span style="border: 1px solid green; height: 100px;">Child 2</span>
          &nbsp;
        </div>
      </div>
      

      【讨论】:

        猜你喜欢
        • 2014-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-08
        相关资源
        最近更新 更多