CSS中div的高度未从容器继承

3

这里有一个容器 div,里面包含两个浮动的 div 和一个普通的 div:

<div style="width: 110%; min-height:250px;overflow:hidden; border: 4px solid red">

  <!-- divI -->
  <div style="float:right; padding:25px; width:35%; border: 6px  gray; border-style: hidden hidden hidden double ">
    ....stuff
  </div>

  <!-- divII -->
  <div style="float:right; padding: 25px; width:35%;  border-left: 6px gray; border-style: hidden hidden hidden double; height:100% ">
    ....stuff
  </div>

  <div>
    .... stuff
  </div>
</div>

两个浮动的 div 在左侧都有灰色边框,分隔了两列。
除了灰色边框之外一切正常。DivII 比 DivI 要短。容器 div 上的红色边框与 div I 的底部边框匹配,但是 divII 的边框没有继承容器的高度,因此太短了。
我知道浮动的 div 会引起这种问题,但我不知道怎么修复它。
2个回答

4
问题在于您在父元素上指定了min-height,但期望子元素继承height。您应该在父元素上使用height或在子元素上使用min-height: inherit
必须还要说的是,您真的不想使用内联样式,主要是由于其高特异性(仅内联!important能够超越它)和在DOM元素中的必要重复。
  1. 在子元素上使用min-height: inherit

.parent {
  width: 110%;
  min-height: 250px;
  overflow: hidden;
  border: 4px solid red;
}

.child {
  float: right;
  padding: 25px;
  width: 35%;
  border-left: 6px gray;
  border-style: hidden hidden hidden double;
  min-height: inherit; /* <-- use min-height here */
  height: 100%;
}
<div class="parent">

  <div class="child">....stuff</div>

  <div class="child">....stuff</div>

  <div>.... stuff</div>
</div>

  1. 在父元素上使用 height 属性:

.parent {
  width: 110%;
  min-height: 250px;
  height: 250px; /* <-- use height here */
  overflow: hidden;
  border: 4px solid red;
}

.child {
  float: right;
  padding: 25px;
  width: 35%;
  border-left: 6px gray;
  border-style: hidden hidden hidden double;
  height: 100%;
}
<div class="parent">

  <div class="child">....stuff</div>

  <div class="child">....stuff</div>

  <div>.... stuff</div>
</div>


我尝试了您建议的方法,即min-height:inherit,但没有任何改变。DivII仍然很短。在容器div中放置特定高度会导致子div被截断。关于内联样式,我在摆弄时使用它来尝试获得我想要的效果,然后在确定它将是什么之后将其移动到CSS页面。 - Betty Mock
@BettyMock 你确定你没有改变其他任何东西吗?我在这里附上了一个实时示例,展示了它的工作原理。点击其中一个片段来运行它们。 - nem035

0
 height:100% 

你在第二个 div 中忘记了

    <div style="width: 110%; min-height:250px;overflow:hidden; border: 4px solid red">

  <!-- divI -->
  <div style="float:right; padding:25px; width:35%; border-left: 6px  gray; border-style: hidden hidden hidden double; height:100%  ">
    ....stuff 1
  </div>

  <!-- divII -->
  <div style="float:right; padding: 25px; width:35%;  border-left: 6px gray; border-style: hidden hidden hidden double; height:100% ">
    ....stuff 2
  </div>

  <div>
    .... stuff
  </div>
</div>

没有任何区别 - Betty Mock

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接