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
You will need some JavaScript to prevent cropping if you don't know the dimension of the image at the time you're writing the css.
<div id="container">
<img src="something.jpg" alt="" />
</div>
<script type="text/javascript">
(function() {
var img = document.getElementById('container').firstChild;
img.onload = function() {
if(img.height > img.width) {
img.height = '100%';
img.width = 'auto';
}
};
}());
</script>
#container {
width: 48px;
height: 48px;
}
#container img {
width: 100%;
}
If you use a JavaScript Library you might want to take advantage of it.
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%);
}
you can use class "img-fluid" for newer version i.e Bootstrap v4.
and can use class "img-responsive" for older version like Bootstrap v3.
Usage:-
img tag with :-
class="img-fluid"
src="..."
Using CSS only:
div > img {
width: auto;
height : auto;
max-height: 100%;
max-width: 100%;
}
I was having a lot of problems to get this working, every single solution I found didn't seem to work.
I realized that I had to set the div display to flex, so basically this is my CSS:
div{
display: flex;
}
div img{
max-height: 100%;
max-width: 100%;
}
Use max-height:100%; max-width:100%;
for the image inside the div.