当内容在相对/绝对位置重叠时,向下推下一个DIV

时间:2018-12-03 16:09:10

标签: html css

我有以下HTML(例如:https://jsfiddle.net/nL3tc7vw/2/):

<div class="parent">

  <img src="https://via.placeholder.com/400x80?text=Image">

  <div class="child">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting.
  </div>

</div>

<div class="next">
  Next div ...
</div>

使用以下CSS:

div.parent {
  position: relative;
  border: 1px solid red;
  width: 400px;
}

div.child {
  border: 1px solid blue;
  position: absolute;
  top: 0;
}

div.next {
  border: 1px solid green;
  width: 400px;
  font-weight: bold;
}

当“子级” DIV内容高度大于图像高度时,如何防止“父级” DIV重叠“下一个” DIV?

基本上,我需要“儿童”中的“文字”位于图片上方,并且不与下一个div重叠。

1 个答案:

答案 0 :(得分:1)

使用z-index校正重叠时,您需要在要执行的操作中添加一个Position图层。我在div.child类中添加了“ position:relative”。这样,IMG位于第一个div的后面,并且不与容器文本重叠。看下面的例子:

我认为 @Mr Lister 对这个答案产生了影响,它在img容器中添加了一个位置:absolute,以控制其当前位置。

div.parent {
  position: relative;
  border: 1px solid red;
  width: 400px;
}

img {
  position: absolute;
  top: 0;
  z-index: 1000;
}

div.child {
  position:relative;
  border: 1px solid blue;
  z-index: 2000;
}

div.next {
  border: 1px solid green;
  width: 400px;
  font-weight: bold;
}
<div class="parent">

  <img src="https://via.placeholder.com/400x80?text=Image">
  
  <div class="child">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting.
  </div>

</div>

<div class="next">
  Next div ...
</div>