CSS3 Rounded Corners: Avoiding Image Clipping Problems

The Scenario

Consider the following HTML+CSS setup: an img element wrapped in a div container with rounded corners (and optionally, a drop shadow); the div is sized to match the image’s dimensions, like so:

<!-- HTML -->

<div class="rounded">
    <img src="…" height="50" width="100" />
</div>
/* CSS */

div.rounded {
    border-radius: 5px;
        -moz-border-radius: 5px;
        -webkit-border-radius: 5px;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.65);
    height: 50px;
    width: 100px; }

The Problem

If you’ve been playing around with CSS3 long enough, chances are you’ve already encountered this common problem: the corners of the image don’t get clipped by the container, although the container’s corners are rounded. A perfectly logical outcome, considering the box model behavior and element hierarchy, but in most cases, it’s not what we want for our layout. (See Figure 1; I added a box-shadow effect in the example to better illustrate to problem.)

Without overflow: hidden
Figure 1. Without overflow: hidden;

The Solution

Most of the solutions available involve setting the image as the container’s background, and either setting the opacity of the image to zero, or removing the image altogether using a script. I wanted none of that; there had to be a much simpler solution.

Then, it hit me:

/* CSS */

div.rounded {
    border-radius: 5px;
        -moz-border-radius: 5px;
        -webkit-border-radius: 5px;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.65);
    height: 50px;
    overflow: hidden;
    width: 100px; }

Bam! (See Figure 2.)

With overflow: hidden
Figure 2. With overflow: hidden;

The Disclaimer

Of course, that is to say:

  • I have not tested this extensively; I only verified this to work in Internet Explorer 9, Google Chrome 11 beta, Safari/Win 5 (technically) and Firefox 4 (but not on Opera 11), and only for a specific HTML setup; your mileage may vary;
  • This solution came pretty late into the game; the browser landscape has seen leaps and bounds in terms of standards support from all the major players (even Internet Explorer, imagine that!), which could factor into the simplicity of this solution versus the earlier ones that came in about a year ago.

The Alternative

Also, because of the ever-improving support for CSS3 across popular browsers, you could alternatively apply border-radius to the img element itself (depending on how your layout is intended to behave, of course).

Let me know if this works for you for a different setup. An HTML sandbox is available for your dissecting pleasure.

You might also like:
  1. Rapid Fire #1: Photo-Realistic
  2. Rapid Fire #5: Image Editing Tricks Part II
  3. Rapid Fire #8: Extracting Logos

4 Responses to “CSS3 Rounded Corners: Avoiding Image Clipping Problems”


Comments are currently closed.