T
19

The one stat that made me rethink my whole grid approach

I was reading through the CSS Grid spec docs last month, not something I do for fun usually, but I was trying to figure out why my layout was acting weird on mobile. Turns out that grid items can overlap by default without any extra code if you place them in the same cell. That blew my mind because I always thought you needed z-index or absolute positioning for overlap. I tested it on a simple 2x2 grid with two items in the same spot and sure enough they stacked right on top of each other. Never realized that was built into the spec from the start. Anyone else stumble on something simple like this that totally changed how you build your grids?
2 comments

Log in to join the discussion

Log In
2 Comments
the_ray
the_ray6d ago
Oh yeah, I actually ran into that same thing a while back too. But idk, I think there's a small catch with it that folks miss sometimes. When you overlap grid items like that, the stacking order actually follows a specific rule based on how you place them in the source code, not just randomly. I tried putting a sidebar and a main content area in the same cell once, and the order in the HTML totally controlled which one sat on top. It's not really a z-index situation unless you want to override it, which is cool but also kinda sneaky if you don't expect it.
2
the_piper
the_piper6d ago
Wait, is that actually right though? I thought source order only matters if items don't have a defined position. Once you place them in the same grid cell with explicit row and column lines, the stacking order is actually based on the last one in the HTML that occupies that space. But if you use grid-column and grid-row to put them in the same spot, the later element in the source code wins unless you mess with z-index. So yeah, source order does matter, but it's not some secret rule - it's just how CSS normally works with everything. Grid doesn't add any special stacking behavior that isn't already there with regular positioning.
5