Reputation: 55
I am trying to make a 50% rounded img inside a simple div. I have tried 2 ways to do it, but obviously neither has worked for me. If it makes something clear, the image, that I'm getting is square
/*HTML*/
<div class="img-container"></div>
/*CSS*/
.img-container {
background: url("../../../../../assets/img/user-photo.svg") no-repeat center top / cover;
height: 125px;
width: 125px;
border-radius: 50%;
}
/*HTML*/
<div class="img-container">
<img src="path_to_img" alt="User photo">
</div>
/*CSS*/
.img-container {
width: 125px;
height: 125px;
img {
width: 100%;
height: 100%;
border-radius: 50%;
}
}
I am getting it quite cropped in the bottom. Are there any other solutions or what I am doing wrong in 2 examples above? Any help appreciate.
Upvotes: 0
Views: 428
Reputation: 5742
This is some simple markup, a div container and the image is enough.
If the image may come in different sizes or shapes, you can use the object-fit
property to make sure it displays correctly regardless. Just make sure you define the explicit size (height and width) you need the image to be, and then you can use object-fit: cover
on the img itself so it maintains its aspect ratio and uses all available space for exmaple.
.img-container {
background-color: purple;
padding: 10px 0;
width: 200px;
}
img {
border-radius: 50%;
width: 100px;
height: 100px;
display: block;
margin: 0 auto;
}
img.rect-img {
object-fit: cover;
}
<div class="img-container">
<img src="https://via.placeholder.com/100" alt="User photo">
</div>
<div class="img-container">
<img class="rect-img" src="https://via.placeholder.com/100x50" alt="User photo">
</div>
Upvotes: 2
Reputation: 3667
It works without any problem. I think your image has some transparent parts.
img {
box-shadow: 2px 2px 5px rgba(0, 0, 0, .4);
}
img.a {
width: 64px;
border-radius: 100%;
}
img.b {
width: 64px;
border-radius: 100%;
object-fit: cover;
width: 64px;
height: 64px;
}
<h1>Non-square image:</h1>
<img class="a" src="https://images.unsplash.com/photo-1579075475207-e59cd9d39be8">
<hr>
<h1>Converted to square using CSS:
<h1/>
<img class="b" src="https://images.unsplash.com/photo-1579075475207-e59cd9d39be8">
Upvotes: 0