fit an image inside div with border-radius?

Viewed 1827

Imagine a parent div with a rounded border-radius. Is there a way to fit an img inside the div so that it also conforms to the rounded border?

.parent-div {
  background-color: gray;
  border-radius: 20px;
}

.image {
  width: 100%
}
<div class="parent-div">
  <img class="image" src="/a-cool-image">
  <p>Some text</p>
</div>

This just results in an image with square corners while the div has rounded corners on the bottom. The only workaround I know is to have the image have the same border-radius property but only on the top two corners. I find that to be an annoying workaround.

3 Answers

You can try this.

.parent-div img {
    -webkit-border-radius: 20px;
    -moz-border-radius: 20px;
    -ms-border-radius: 20px;
    -o-border-radius: 20px;
    border-radius: 20px;
}
.image {
  width: 100%
}
<div class="parent-div">
  <img class="image" src="https://www.w3schools.com/howto/img_avatar.png">
  <p>Some text</p>
</div>

Another workaround might be using CSS. You can set the radius property for individual corners. This is an example with rounded corners at the top, and square corners at the bottom:

img.yourclass { 
-webkit-border-top-left-radius: 20px;
-webkit-border-top-right-radius: 20px;
-moz-border-radius-topleft: 20px;
-moz-border-radius-topright: 20px;
border-top-left-radius: 20px;
border-top-right-radius: 20px;
}

Check out this website to generate the CSS code: https://border-radius.com/

Related