How do I prevent an image from overflowing a rounded corner box?

Viewed 59175

If I use this code, the image isn't clipped by the div's rounded corners (resulting in the image's square corners covering up the div's rounded ones):

<div style="border-radius: 1em; -moz-border-radius: 1em; -webkit-border-radius: 1em; overflow:hidden;">
    <img src="big-image.jpg" />
</div>

Does anyone know how to get a rounded corder div to prevent a child image from overflowing?

10 Answers

This may or may not work in your situation, but consider making the image a CSS background. In FF3, the following works just fine:

<div style="
  background-image:   url(big-image.jpg);
  border-radius:      1em;
  height:             100px;
  -moz-border-radius: 1em;
  width:              100px;"
></div>

I'm not sure there's another workaround — if you apply a border to the image itself (say, 1em deep), you get the same problem of square corners.

Edit: although, in the "adding a border to the image" case, the image inset is correct, it's just that the image isn't flush with the div element. To check out the results, add style="border:1em solid black;border-radius:1em;-moz-border-radius:1em;" to the img tag (with width and height set appropriately, if necessary).

Even when overflow is set to hidden, border-radius does not clip its content. This is by design.

One solution would be to set border-radius on the image as well as its container.

<div style="border-radius: 16px; ...">
    <img src="big-image.jpg" style="border-radius: 16px; ..." />
</div>

Another way would be to set the image as the background of the container using background-image; but there are issues with this method in Firefox before version 3 (see this bug) - not that that need bother you too much.

Try this workaround:

  1. The image in img tag is present and there you set the width and height.
  2. Then hide it with visibility:hidden. The width and height stay intact.
  3. After that you'll set the same source as background image an it will clipped.

<a class="thumb" href="#" style="background-image: url('./img/pic1.jpg');" title="Picture">
  <img border="0" src="./img/pic1.jpg" alt="Pic" height="100" width="150" />
</a>

#page .thumb {
background-repeat: no-repeat;
background-position: left top;
border: 3px #e5dacf solid;
display: block;
float: left;}

#page .thumb img {
display: block;
visibility: hidden;}

If you make the image a background image instead of contents, the image won't clip the rounded corners (at least in FF3).

You could also add a padding to the div, or margin for the image to add extra padding between the rounded border and the image.

You need to specify an exact width and heigth with overflow:hidden, if you want your div to clip your image

Related