Search code examples
htmlcssreactjsborder-radius

image with border radius does not fill the div


I was trying to render an image inside a div which has curved borders. I am experiencing an issue where the image does not completely fill the div, despite both having the same border radius and dimensions.

output

Here is how i am rendering the image inside the div

<div className={"container"}>
    <img
      alt={"thumb"}
      className={"img"}
      src={
        "https://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/Gull_portrait_ca_usa.jpg/300px-Gull_portrait_ca_usa.jpg"
      }
    />
  </div>

and here are the css classes

.container {
  height: 32px;
  width: 32px;
  border-radius: 8px;
  border: 1px solid grey;
}

.img {
  height: 32px;
  width: 32px;
  border-radius: 8px;
}

Here is the link to a live codesandbox environment link


Solution

  • I prefer to apply overflow: hidden to the container, unless some child content needs to be visible outside of the container. When used with a border radius it masks off the parts of the child that overflow:

    .container {
      height: 32px;
      width: 32px;
      border-radius: 8px;
      border: 1px solid grey;
      overflow: hidden;
      
    /*  just to make it bigger  */
      transform: scale(15);
      transform-origin: top left;
    }
    
    .img {
      height: 32px;
      width: 32px;
    }
    <div class="container">
        <img
            alt="thumb"
            class="img"
            src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/Gull_portrait_ca_usa.jpg/300px-Gull_portrait_ca_usa.jpg"
        />
    </div>

    Note: Make sure you remove any border-radius set to the image inside.