【问题标题】:How to inherit height of a sibling [duplicate]如何继承兄弟姐妹的身高[重复]
【发布时间】:2020-09-04 08:04:00
【问题描述】:

假设我有一个包含 2 个元素的容器 div

<div class="container" >  

  <div class="section" ></div>
  <div class="text" >Some text</div>

</div>

我的问题是,如何编写 CSS 以使包含所有文本的 .text div 的高度与 .section div 一样大,例如如果

.section{
  height: 450px;
}

那么 .text 的高度也是 450px。或者我需要javascript来做到这一点

【问题讨论】:

  • container 设为 flex 父级。
  • 列布局还是行布局?所以我可以带上正确的副本

标签: html css


【解决方案1】:

您可以给它们两个相同的百分比高度,然后根据父级设置高度

.section {
  height: 50%;
  background: red;
}

.text {
  background: green;
  height:50%;
}

.container{
height:450px}
<div class="container">

  <div class="section"></div>
  <div class="text">Some text</div>

</div>

【讨论】:

  • 在我的特定示例中,父母或两个孩子都没有设定高度。 .section 元素的高度由内部渲染的图像数量决定(假设用户决定)。 .container 的高度由它的子项(所以 .section)决定,然后 .text 的大小应该与 .section
【解决方案2】:

您应该将文本 div 放在部分 div 中,以便它影响更改,如下所示:

 <div class="section" >
      <div class="text" >Some text</div>
    </div>

.section {
  height: 450px;
  background: red;
}

【讨论】:

    猜你喜欢
    • 2019-05-06
    • 2019-08-29
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2013-06-07
    相关资源
    最近更新 更多