how to overlap a top <div> and a bottom <div> into an image without generating ugly/messy white spaces?

Viewed 120

I have a top div, an image, and a bottom div in my html and I want to overlap the 2 divs into my image, the first div should cover some area in the top part of the image, and the bottom div should cover some area in the bottom part of the image, the div should be the one covering the image (on front of display). how would I do that in a clean way (without leaving white spaces) and make it responsive in respect to the width of the view or parent div?

here is my html

* {
  padding: 0px;
  margin: 0px;
}

#image {
  max-width: 100%;
}

.rects {
  height: 100px;
}

#rect-top {
  background-image: linear-gradient(45deg, rgba(0, 194, 228, 0.75), rgba(214, 0, 203, 0.479));
}

#rect-bottom {
  background-image: linear-gradient(45deg, rgba(214, 0, 203, 0.479), rgba(0, 194, 228, 0.75));
}
<h1>Start</h1>
<div id="rect-top" class="rects"></div>
<img id="image" src="image-with-gradient.jpg">
<div id="rect-bottom" class="rects"></div>
<h1>End</h1>

this is what I want to achieve:

enter image description here

as you can see there is no white space before and after the h1 tags

1 Answers

Wrap your image and overlapping divs in a div. Inside that, position your overlap div elements absolute.

As a sidenote, don't use id for styling purposes. Also note that any id in your page can only live on a single element; id must be unique per-document.

Instead of creating meaningless markup for the gradients, you can use the pseudo elements ::before and ::after here.

* {
  padding: 0;
  margin: 0;
}

.image-container {
  padding: 50px 0;
  position: relative;
}

.image {
  max-width: 100%;
}

.image-container::before,
.image-container::after {
  content: '';
  height: 100px;
  position: absolute;
  width: 100%;
}

.image-container::before {
  background-image: linear-gradient(45deg, rgba(0, 194, 228, 0.75), rgba(214, 0, 203, 0.479));
  top: 0;
}

.image-container::after {
  background-image: linear-gradient(45deg, rgba(214, 0, 203, 0.479), rgba(0, 194, 228, 0.75));
  bottom: 0;
}
<h1>Start</h1>
<div class="image-container">
  <img class="image" src="https://placekitten.com/g/1920/1080">
</div>
<h1>End</h1>

This also makes the use of z-index obsolete because elements with position: absolute are automatically on top of unpositioned elements.

Related