Published on

How to Position a Div on Top of Another in Tailwind CSS

Authors
  • Name
    Ripal & Zalak
    Twitter

How to Position a Div on Top of Another in Tailwind CSS

When working with Tailwind CSS, you may need to stack one div on top of another. This is commonly required in layouts involving maps, overlays, or modal components.

Solution using absolute, relative, and z-index

Here's a simple way to place one div over another using Tailwind CSS:

<div className="relative flex h-screen w-full items-center justify-center bg-gray-200">
  {/* Background div */}
  <div className="relative z-0 h-96 w-96 bg-green-400">
    <p className="text-bold font-serif italic">Map</p>
  </div>
  {/* Foreground div */}
  <div className="absolute inset-0 z-10 flex items-center justify-center">
    <p className="bg-white p-2 text-2xl font-bold">This should be on top of the map</p>
  </div>
</div>

Explanation:

  1. The outermost div is given relative positioning so that the absolute children are positioned relative to it.
  2. The first inner div (bg-green-400) serves as the background.
  3. The second inner div (absolute inset-0) is positioned absolutely, covering the entire background div.
  4. The z-10 ensures that the overlay text is on top.

Alternative Approach: Using CSS Grid

If you prefer an alternative way without using absolute positioning, Tailwind's CSS Grid can help:

<div className="grid">
  <div className="col-start-1 row-start-1 bg-green-400 p-4">A</div>
  <div className="col-start-1 row-start-1 bg-blue-400 p-4 text-white">B</div>
</div>

This method stacks both divs on top of each other within the same grid cell.

Responsive Overlay Navbar Example

For layouts requiring an overlay navbar on mobile screens, use absolute, z-index, and hidden classes:

<div className="relative flex h-screen bg-gray-500">
  <div className="text-4xl">Main content</div>
  <div className="absolute inset-y-0 left-0 z-10 w-1/3 bg-green-400 md:hidden">Mobile Navbar</div>
</div>

FAQs

Why is my absolute div not appearing on top?

Make sure the parent div has relative positioning and the z-index of the overlay is higher than the background div.

How do I make the overlay responsive?

Use Tailwind’s md:hidden and md:block to toggle visibility on different screen sizes.

Can I use fixed instead of absolute?

Yes, fixed can be used if you want the overlay to remain on top regardless of scrolling.