- Published on
How to Position a Div on Top of Another in Tailwind CSS
- Authors
- Name
- Ripal & Zalak
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.
absolute
, relative
, and z-index
Solution using 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:
- The outermost
div
is givenrelative
positioning so that the absolute children are positioned relative to it. - The first inner
div
(bg-green-400
) serves as the background. - The second inner
div
(absolute inset-0
) is positioned absolutely, covering the entire backgrounddiv
. - 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
absolute
div not appearing on top?
Why is my 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.
fixed
instead of absolute
?
Can I use Yes, fixed
can be used if you want the overlay to remain on top regardless of scrolling.