CSS overflow hidden with absolute position

HtmlCss

Html Problem Overview


I want to absolute position an image that I will be moving around in a div and want anything that extends outside the div to be clipped. Here is an example of the problem:

<html>
<body>
  <div style="width: 500px; height: 200px; border: 1px solid black; overflow: hidden;">
    <div style="width: 200px; height: 50px; margin: auto; border: 1px solid black; background: gray;">On top of image.</div>
    <div style="position: absolute; top: 10px; left: 250px; z-index: -1;"><img src="http://www.google.com/logos/worldcupfinale10-hp.gif" /></div>
  </div>
</body>
</html>

So, I want the right edge of the logo to not display. Ideas?

Html Solutions


Solution 1 - Html

Try adding position: relative to your outer div. This will position the image relative to that div (honoring the overflow style) instead of relative to the page.

Example:

<html>
<body>
  <div style="position: relative; width: 500px; height: 200px; border: 1px solid black; overflow: hidden;">
    <div style="width: 200px; height: 50px; margin: auto; border: 1px solid black; background: gray;">On top of image.</div>
    <div style="position: absolute; top: 10px; left: 250px; z-index: -1;"><img src="http://www.google.com/logos/worldcupfinale10-hp.gif" /></div>
  </div>
</body>
</html>

See it on JS Bin

Solution 2 - Html

Since the image's container is positioned absolutely, it is outside of the flow of the "containing" div.

Your choices are to either position relatively or to adjust the dimensions of the absolutely-positioned div, dynamically, with jQuery.

Solution 3 - Html

Move the position absolute to the image, then add the relative to the parent container. Worked for me in a similar situation.

<html>
<body>
  <div style="width: 500px; height: 200px; border: 1px solid black; overflow: hidden;">
    <div style="width: 200px; height: 50px; margin: auto; border: 1px solid black; background: gray;">On top of image.</div>
    <div style="position: relative; overflow:hidden;"><img style="position: absolute; top: 10px; left: 250px; z-index: -1;" src="http://www.google.com/logos/worldcupfinale10-hp.gif" /></div>
  </div>
</body>
</html>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid AView Question on Stackoverflow
Solution 1 - HtmlBrian MoeskauView Answer on Stackoverflow
Solution 2 - HtmlBrock AdamsView Answer on Stackoverflow
Solution 3 - HtmlChristos HrousisView Answer on Stackoverflow