【问题标题】:Adding margin to a div with an overflowing child向带有溢出子元素的 div 添加边距
【发布时间】:2020-04-24 22:22:46
【问题描述】:

我遇到了一个问题,我正在尝试将底部边距添加到具有溢出高度的子元素的 div 中。 Dom 元素正好位于父 div 下方,同时被子 div 覆盖,但我希望 dom 元素位于子 div 下方。我正在寻找的设计看起来像这样:

------------------------------
|                             |
|          Parent             |
|  -------------------------  |
|__|_______________________|__|
   |                       |
   |       child           |
   |_______________________|
 /* ------margin -------- */
 content

我尝试使用height: fit-content 在整个事物周围添加另一个 div,但这只会使高度等于父 div,不包括子 div。有没有办法做到这一点?

【问题讨论】:

  • 如果孩子为 150 像素且重叠部分为 50 像素,则给出(孩子高度 - 重叠部分)的父级边距底部。给父margin-bottom: 100px;
  • 不幸的是,我不知道孩子的身高,它们是根据宽度缩放的图像。如果可以的话,我可以手动在底部添加边距
  • 可以用js获取孩子身高。然后用它来设置父边距底部。

标签: html css reactjs


【解决方案1】:

我认为不改变结构就无法做到这一点。基本上,这就是“溢出”的意思。

我会尝试让你的“父母”和“孩子”兄弟姐妹成为一个共同的父母。像现在一样定位它们,没有溢出。然后,它下面的内容将正确对齐,您可以使用边距。

类似这样的东西(填充不相关,仅用于说明):

#new-parent {
  border: 1px solid red;
  margin-bottom: 2rem;
}

#old-parent {
  background: orange;
  padding: 2rem;
}

#old-child {
  background: lightblue;
  margin: -2rem 2rem 0 2rem;
  padding: 3rem;
}

#content {
  background: lightgray;
  padding: 1rem;
}
<div id="new-parent">
  <div id="old-parent">
    old-parent
  </div>
  <div id="old-child">
    old-child
  </div>
</div>

<div id="content">
  rest of the content
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-25
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多