【问题标题】:How to grow parent height div based on absolute child's height如何根据绝对孩子的身高增长父母身高div
【发布时间】:2020-05-09 07:19:58
【问题描述】:

我正在尝试在 Gatbsy(React) 应用程序中实现以下布局。我有这样的样子。问题是白色方块的高度会根据内容而改变。如果这个高度发生变化,蓝色的高度也需要改变。页面需要始终看起来像附件中的图片,这意味着无论白色方块的高度如何,它总是需要略高于蓝色方块。

我正在使用 Sass(SCSS)。

代码笔: https://codepen.io/devpato/pen/ZEYwexw

CSS

 .header, .footer {
      width: 100%;
      height: 200px;
      background-color: green;
    }

    .blue {
      position: relative;
      /* Height can't have a set value */
      height: 400px;
      background-color: blue;
      width: 100%;

      .white {
      height: 400px;
      position: absolute;
      background-color: white;
      left: 0;
      right: 0;
      margin: 0 auto;
      top: -24px;
      width:  80%;
     }
    }

HTML

<div class="container">
  <div class="header"></div>
  <div class="blue">
       <div class="white"></div>
  </div>
  <div class="footer"></div>
</div>

【问题讨论】:

  • 为什么要强制将子 div 设置为绝对值,以用于重叠父级?
  • @Hanif 正确!重叠顶部的绿色正方形...当然。如果您有更好的方法来实现这一点,我愿意:)
  • 然后只需删除父高度并保留子高度并将子设置为相对。

标签: javascript html css reactjs sass


【解决方案1】:

然后只需删除父高度并保留子高度并将子设置为相对如下:

.blue {
  position: relative;
  /* Hight can't have a set value */
  /*height: 400px;*/
  background-color: blue;
  width: 100%;
  .white {
    height: 400px;
    position: relative;
    background-color: white;
    left: 0;
    right: 0;
    margin: 0 auto;
    top: -24px;
    width:  80%;
 }
}

另见此处:codepenexample

【讨论】:

    【解决方案2】:

    从父级移除高度并在子级中添加相对位置而不是绝对位置

    .blue {
      position: relative;
      background-color: blue;
      width: 100%;
      .white {
      height: 400px;
      position: relative;
      background-color: white;
      left: 0;
      right: 0;
      margin: 0 auto;
      top: -24px;
      width:  80%;
     }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-16
      • 2019-06-20
      • 2022-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多