CSS: How to have position:absolute div inside a position:relative div not be cropped by an overflow:hidden on a container

avernet picture avernet · Feb 11, 2010 · Viewed 107.4k times · Source

I have 3 levels of div:

  • (In green below) A top level div with overflow: hidden. This is because I want some content (not shown here) inside that box to cropped if it exceeds the size of the box.
  • (In red below) Inside this, I have div with position: relative. The only use for this is for the next level.
  • (In blue below) Finally a div I take out of the flow with position: absolute but that I want positioned relative to the red div (not to the page).

I'd like to have the blue box be taken out of the flow and expand beyond the green box, but be positioned relative to the red box as in:

However, with the code below, I get:

And removing the position: relative on the red box, now the blue box is allowed to get out of the green box, but is not positioned anymore relative to the red box:

Is there a way to:

  • Keep the overflow: hidden on the green box.
  • Have the blue box expand beyond the green box and be positioned relative to red box?

The full source:

Answer

avernet picture avernet · Feb 11, 2010

A trick that works is to position box #2 with position: absolute instead of position: relative. We usually put a position: relative on an outer box (here box #2) when we want an inner box (here box #3) with position: absolute to be positioned relative to the outer box. But remember: for box #3 to be positioned relative to box #2, box #2 just need to be positioned. With this change, we get:

And here is the full code with this change:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <style type="text/css">

            /* Positioning */
            #box1 { overflow: hidden }
            #box2 { position: absolute }
            #box3 { position: absolute; top: 10px }

            /* Styling */
            #box1 { background: #efe; padding: 5px; width: 125px }
            #box2 { background: #fee; padding: 2px; width: 100px; height: 100px }
            #box3 { background: #eef; padding: 2px; width: 75px; height: 150px }

        </style>
    </head>
    <body>
        <br/><br/><br/>
        <div id="box1">
            <div id="box2">
                <div id="box3"/>
            </div>
        </div>
    </body>
</html>