【问题标题】:How do I set a floating element automatically fill the remaining height of its parent element (height not fixed and displayed as a table)?如何设置浮动元素自动填充其父元素的剩余高度(高度不固定并显示为表格)?
【发布时间】:2018-05-24 13:39:02
【问题描述】:

我有以下代码:

.parent {width: 960px; display: table}

.1 {
  width: 45%;
  margin: 20px;
  float: left;
  height: 1000px; /* it can be smaller or bigger than this value to fit its content */
}

.2 {
  width: 45%;
  margin: 20px;
  float: right;
  height: 200px;
}

.3 {
  width: 45%;
  margin: 20px;
  float: right;
}
<div class="parent">
  <div class="1">1</div>
  <div class="2">2</div>
  <div class="3">3</div>
</div>

如何为“3”类编写 CSS,使其高度自动填充表格的剩余高度(在上面的例子中,720 像素,因为我假设父元素的高度也为 1000 像素)?请注意,“1”类的高度可以根据其内容而变化。

题外话:除了我现在使用的代码(仅使用CSS和HTML)之外,有没有更好的方法让它看起来像下图?

The Image of the Table

【问题讨论】:

  • 你必须做出选择。浮动或显示。根据您的图片,display:grid; 将是最好且更易于使用的。示例:codepen.io/gc-nomade/pen/WJWyJr
  • 可以用float代替吗?不幸的是,我既没有被教过如何使用 display:grid 也没有被教过您在示例中包含的任何属性。如果不可能,我会尝试将它们全部查找。 @G-Cyr
  • float 并不意味着绘制相同高度的列。 display: table, flex 和 grid 可以帮助你。我相信这里只有网格才会有效:(
  • ...codepen再次上线...codepen.io/gc-nomade/pen/BxEPdp
  • @G-Cyr 嗨,我刚刚读到这个:developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/…。我现在明白你的代码是什么意思,但我确实遇到了第 33 行的问题。我尝试删除它们,数字消失了。我可以在哪个部分了解这些属性(网格、表格、CSS 或其他)?另外,如果有经验法则,我应该什么时候使用 float、display:table、flex 或 grid?

标签: html css html-table css-float


【解决方案1】:

试试这个。第三个元素(绿色)将根据.one 的高度进行调整。但它是基于.two 具有固定尺寸的假设来实现的。

.parent {
    width: 960px;
    border: solid 2px #999;
    float: left;
    position: relative;
}
.one {
    width: 50%;
    float: left;
    height: 1000px;
    background: #ccc;
}
.two {
    width: 50%;
    float: right;
    height: 200px;
    background: #aaa;
}
.three {
    position: absolute;
    top: 200px;
    left: 50%;
    right: 0;
    bottom: 0;
    background: green;
}
<div class='parent'>
    <div class='one'>one</div>
    <div class='two'>two</div>
    <div class='three'>three</div>
</div>

【讨论】:

  • 我从来没有使用过“位置”,所以我读到了这个:developer.mozilla.org/en-US/docs/Web/CSS/position。根据我的阅读,父元素上的 position:relative 是必要的,这样 .three 知道在哪里计算它的“左”和“上”,右(在这种情况下,“父”)?另外,为什么必须在“父”上使用“float:left”?我试过没有浮动,它坏了。题外话:在我专门在“粘性定位”部分发送的链接上,为什么“A”即使是粘性的也会消失?是因为“B”替换了“A”还是因为它已经超出了“A”的div? @Pons
  • 1.如果不为父元素应用相对位置,则绝对元素(.three)将相对于body定位。所以 left:50% 将根据您的浏览器窗口计算。同样,其他偏移量也是如此。 2. 由于子元素是浮动元素,如果不为父元素应用浮动,则父元素不会随着子元素的大小一起拉伸。如果发生这种情况,在我们的例子中,“bottom:0”将被破坏为 .three。如果您想避免浮动,您可以为父级应用“溢出:隐藏”。但要注意,如果有东西,它会隐藏溢出。
  • 感谢您的回答!如果我仍在等待其他用户的评论回复,我应该接受您的回答吗? @Pons
  • 欢迎您!全取决于你。干杯!