How to overlay one div over another div ?

To overlay one <div> over another in CSS, use positioning and z-index. Here are three common methods:

1. Using position: absolute (Most Common)

<div class="container">
  <div class="base-div">Base Div</div>
  <div class="overlay-div">Overlay Div</div>
</div>
.container {
  position: relative; /* Required for absolute positioning context */
  width: 300px;
  height: 200px;
}

.base-div {
  width: 100%;
  height: 100%;
  background: lightblue;
}

.overlay-div {
  position: absolute;
  top: 20px;   /* Position relative to container */
  left: 20px;
  width: 50%;
  height: 50%;
  background: rgba(255, 0, 0, 0.5); /* Semi-transparent red */
  z-index: 1; /* Ensures overlay is above base div */
}

2. Using CSS Grid

.container {
  display: grid;
  width: 300px;
  height: 200px;
}

.base-div, .overlay-div {
  grid-area: 1 / 1; /* Place both divs in the same grid cell */
}

.overlay-div {
  align-self: start; /* Adjust position */
  justify-self: start;
  z-index: 1;
  background: rgba(0, 255, 0, 0.5);
}

3. Using Flexbox

.container {
  display: flex;
  width: 300px;
  height: 200px;
}

.base-div {
  width: 100%;
  height: 100%;
  background: lightblue;
}

.overlay-div {
  position: absolute; /* Still use absolute positioning */
  top: 20px;
  left: 20px;
  z-index: 1;
}

Key Concepts

  1. position: relative on the container creates a positioning context for child elements.
  2. position: absolute removes the overlay from the normal document flow.
  3. z-index controls stacking order (higher values appear on top).
  4. Transparency is achieved with rgba() or opacity.

Common Issues & Fixes

ProblemSolution
Overlay not appearingEnsure z-index is higher than the base div’s.
Overlay positioned incorrectlyCheck parent’s position: relative.
Overlay overflowing containerAdjust top, left, right, or bottom values.

Leave a Reply

Your email address will not be published. Required fields are marked *