I have a 48x48 div and inside it there is an img element, I want to fit it into the div without losing any part, in the mean time the ratio is kept, is it achievable using h
Setting the photo as a background image will give us more control over size and placement, leaving the img tag to serve a different purpose...
Below, if we want the div to be the same aspect ratio as the photo, then placeholder.png is a small transparent image with the same aspect ratio as photo.jpg. If the photo is a square, it's a 1px x 1px placeholder, if the photo is a video thumbnail, it's a 16x9 placeholder, etc.
Specific to the question, use a 1x1 placeholder to maintain the div's square ratio, with a background image using background-size to maintain the photo's aspect ratio.
I used background-position: center center; so the photo will be centered in the div. (Aligning the photo in the vertical center or bottom would get ugly with the photo in the img tag.)
div {
background: url(photo.jpg) center center no-repeat;
background-size: contain;
width: 48px; // or a % in responsive layout
}
img {
width: 100%;
}
To avoid an extra http request, convert the placeholder image to a data: URL.