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
For me, the following CSS worked (tested in Chrome, Firefox and Safari).
There are multiple things working together:
max-height: 100%;, max-width: 100%; and height: auto;, width: auto; make the img scale to whichever dimension first reaches 100% while keeping the aspect ratioposition: relative; in the container and position: absolute; in the child together with top: 50%; and left: 50%; center the top left corner of the img in the containertransform: translate(-50%, -50%); moves the img back to the left and top by half its size, thus centering the img in the containerCSS:
.container {
height: 48px;
width: 48px;
position: relative;
}
.container > img {
max-height: 100%;
max-width: 100%;
height: auto;
width: auto;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}