I believe, every front-end developer encountered this situation, at least once. Let’s say you need to absolute position something… And then you try to move it in some direction, and boom it disappears… You forgot the parent was set to overflow:hidden
and now your element is lost in the hidden
infinite vacuum.
Well, usually it ends by putting the absolute
element outside of the annoying overflow:hidden
parent, and you grumbling about how CSS sucks and so on… Actually you’re quite right. CSS do sucks a lot, even CSS3, I mean … ok no troll here 🙂
Let me show you a neat trick.
But first, if you’re trying to mess with these absolute/relative properties you really should be aware of these few important rules:
- An absolutely positioned element is actually positioned regarding a
relative
parent, or the nearest foundrelative
parent, which means it bubbles up the DOM until it finds arelative
context to apply the positioning. - If no relative parent is found it will then reach the highest possible « container », which is the browser window, aka the
viewport
(or thedocument
maybe, or thewindow
… ? hey you know what, I’m not a W3C expert ok!). - BTW, this is probably why they called it « re-la-tive », just sayin’ 😛
- It works the same if the parent is set to
absolute
instead ofrelative
(anabsolute
inside anotherabsolute
) the first absolute acts as the positioning context for the second absolute.
Anyway, here our main problem is that the relative
parent is also the overflow:hidden
one. Well, if we simply move the position
rule to put it just one level above, then the problem will be solved. True. Isn’t that just magic? Actually no, it’s not magic.
And let me prove what I’m saying.
HTML
<div class="parent">
<div class="child"></div>
</div>
CSS
.parent { position: relative; overflow: hidden; } .child { position: absolute; top: -10px; left: -5px; }
Result
Indeed, we can actually see that the little blue square is partially hidden by its overflow hidden parent.
Now the solution
Now let’s add another parent and move the position:relative
one level up (or, in your context, you could maybe simply use an existing upper parent).
HTML
<div class="grand-parent">
<div class="parent">
<div class="child"></div>
</div>
</div>
CSS
.grand-parent { position: relative; } .parent { /*position: relative;*/ overflow: hidden; } .child { position: absolute; top: -10px; left: -5px; }
Result
Magic.
Ressources
Thierry Koblentz’s article explaining different techniques to « clear floats » AND showing this clever trick.
* The post itself
* The overflow hidden / absolute demo (which isn’t there anymore apparently…)