css 如何将子对象放置< div>在父对象之上< div>,并使父对象< div>根据子对象调整其高度< div>?

oprakyz7  于 2023-03-20  发布在  其他
关注(0)|答案(2)|浏览(159)

那么,如何确保容器2和3根据容器1自动调整大小呢?
我看过一个similar question here。根据这篇文章,它提到了flexbox和grid要考虑这个而不是position:absolute。但是我不太明白如何在我的场景中使用它们。请帮助我如何处理这个问题?
已尝试根据父div顶部的子div动态更改父div。

o2gm4chl

o2gm4chl1#

仅根据屏幕截图,我将其实现为两个元素:2和3将是具有非常大的蓝色上边界和灰色背景颜色的单个div;包含文本的div将位于其内部,并具有负的顶部边距,以使其与蓝色边框重叠:

#container {
  padding: 2em;
  background-color: lightgray;
  border-top: 2em solid darkblue;
}

#inner {
  background-color: white;
  margin-top: -3em;
  padding: 1em;
}
<div id="container">

  <div id="inner">
    Lorem ipsum dolor sit etcetera. Lorem ipsum dolor sit etcetera. Lorem ipsum dolor sit etceteraLorem ipsum dolor sit etcetera. Lorem ipsum dolor sit etceteraLorem ipsum dolor sit etcetera. Lorem ipsum dolor sit etcetera. 
    Lorem ipsum dolor sit etcetera. Lorem ipsum dolor sit etcetera. Lorem ipsum dolor sit etceteraLorem ipsum dolor sit etcetera. Lorem ipsum dolor sit etceteraLorem ipsum dolor sit etcetera. Lorem ipsum dolor sit etcetera. 
    Lorem ipsum dolor sit etcetera. Lorem ipsum dolor sit etcetera. Lorem ipsum dolor sit etceteraLorem ipsum dolor sit etcetera. Lorem ipsum dolor sit etceteraLorem ipsum dolor sit etcetera. Lorem ipsum dolor sit etcetera. 
  </div>
</div>

正常的、未修改的文档流将为您提供所需的大小调整,因为容器将自然地调整大小以适应其内容。
(In一般情况下,position:absolute会干扰正常的文件流程,因此需要精确避免;一旦你开始指定元素的精确绝对位置,你就必须对元素周围的所有东西都这样做。2一旦你开始考虑不同的屏幕尺寸,情况就会变得很糟糕。

eh57zj3b

eh57zj3b2#

如果你想特别使用三个元素,就像这样做:

#div1 {
  position: relative;
  padding: 2em;
  background-color: lightgray;
}

#div2 {
  position: absolute;
    background-color: darkblue;
  height: 3em;
  top: 0;
  left: 0;
  width: 100%;
}

#div3 {
  position: relative;
  background-color: white;
  padding: 1em;
  z-index: 1;
}
<!DOCTYPE html>
<html>
  <body>
    <div id="div1">
      <div id="div2"></div>
      <div id="div3">
        So how do I make sure that the containers 2 & 3 automatically re-size based on the container 1 ? I have seen a similar question here. As per this post, it is mentioned that the flexbox and grid are to be considered for this instead of position:absolute. But I couldn't quite understand how to use those in my scenario. Please help me on how should I approach this ? Tried to change the parent div dynamically based on the child div which is on top of the parent div.So how do I make sure that the containers 2 & 3 automatically re-size based on the container 1 ? I have seen a similar question here. As per this post, it is mentioned that the flexbox and grid are to be considered for this instead of position:absolute. But I couldn't quite understand how to use those in my scenario. Please help me on how should I approach this ? Tried to change the parent div dynamically based on the child div which is on top of the parent div.
      </div>
    </div>
  </body>
</html>

相关问题