在没有固定高度的两个div的中间覆盖div

时间:2020-07-22 07:15:50

标签: html css

我想将<div>覆盖在两个<div>的顶部,并将其布置在这两个之间。

This答案非常接近我想要实现的答案,但是答案不是很实际,因为它明确设置了基础和重叠的<div>的高度。我想要一个不设置这些高度而是根据情况得出的解决方案。

Desired output

到目前为止,我一直在尝试这个JSFiddle(我正在使用Bootstrap 4.5.0)。这相当接近,但是.second <div>的margin-top是手动设置的,导致.second div的顶部边缘未触及.first div的底部边缘。

2 个答案:

答案 0 :(得分:1)

如果将.overlay包裹在div中并设置position: relative;

然后,在覆盖图position: absolute; transform: translateY(-50%);上,它将相对于底部div的顶部定位,以便无论.first中有多少文本,或者屏幕的大小如何,位置将保持不变。

.first {
  background-color: lightgreen;
  padding-bottom: 4em;
  z-index: 0;
}

.second {
  background-color: rgba(124, 150, 80, 0.9);
  padding-top: 4em;
}

.overlay-wrapper {
  position: relative;
}

.overlay {
  position: absolute;
  padding: 1em;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  margin: 0 5em 0 0;
  transform: translateY(-50%);
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css" rel="stylesheet" />
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.js"></script>
<div class="wrapper">
  <div class="first">Some text content goes here. Since the content is not fixed, I don't want to set a fixed height. Some text content goes here. Since the content is not fixed, I don't want to set a fixed height. Some text content goes here. Since the content is not fixed,
    I don't want to set a fixed height.</div>
  <div class="overlay-wrapper">
    <div class="overlay">here comes the overlay div that should come between and overlap first and second div. again, the height of this div is not explicitly set.</div>
  </div>
  <div class="second">Some text content goes here. Since the content is not fixed, I don't want to set a fixed height.</div>
</div>

答案 1 :(得分:0)

如果 .div1 .div2 的背景是纯色,则可以使用以下方法:

.wrapper {
    overflow: hidden;
}
.div1 {
    background: #F19063;
}
.div2 {
    background: #A44691;
}
.div3 {
    position: relative;
    background: #70BB86;
    width: 100%;
    max-width: 300px;
}
.div3:before {
    content: '';
    background: #F19063;
    position: absolute;
    left: 100%;
    top: 0;
    height: 50%;
    width: 100vw;
}
.div3:after {
    content: '';
    background: #A44691;
    position: absolute;
    left: 100%;
    bottom: 0;
    height: 50%;
    width: 100vw;
}
<div class="wrapper">
  <div class="div1">Lorem <br>Lorem <br>Lorem <br></div>
  <div class="div3">Lorem <br>Lorem <br></div>
  <div class="div2">Lorem <br>Lorem <br>Lorem <br></div>
</div>

PS:您需要处理 .div3:before .div3:after 的溢出。