I\'d like to fill a div with an img
, keeping aspect ratio and stretching either width or height as much as required to fit in.
use background-size:cover
div{
background-image:url(http://placekitten.com.s3.amazonaws.com/homepage-samples/200/140.jpg);
background-size:cover;
}
<div style="width:80px;height:80px;"></div>
.thumb {
max-width:100%;
height:auto;
}
Or ( to allow scale up and down, which will look pixelated if you scale up, where the above will only scale to the max size of the image )
.thumb {
width:100%;
height:auto;
}
Is what you are looking for.
More info on responsive images:
http://demosthenes.info/blog/586/CSS-Fluid-Image-Techniques-for-Responsive-Site-Design
http://www.w3schools.com/css/css_rwd_images.asp
the following did the trick:
width:100%;
height:100%;
object-fit: cover;
overflow: hidden;
Using max-width
, the image will be contained inside the div, there will be no overflow.
If you use min-width
instead, the shorter side will be exactly 100% of the div while the other side can be longer.
To center the image, we can use translate and relative positioning.
The following code works.
div {
overflow: hidden;
}
.thumb {
min-width: 100%;
min-height: 100%;
transform: translate(-50%, -50%);
position: relative;
left: 50%;
top: 50%;
}
Not sure if anyone still looking at this post. I came across this while I was looking for a way to fit a image into a < div > without getting the unwanted white space around the image, because I was using hover & stick-out effect. I was inspired by Matt's solution. Instead of
.thumb {
max-width:100%;
height:auto;}
I added
.thumb {
max-width:100%;
max-height:100%;
height:auto;}
Now my images fit in to the < div > perfectly without having those white space stick out with the image.
To keep an image's aspect ratio, just specify one dimension:
div {
width: 80px;
height: 80px;
border: 2px solid red;
overflow: hidden;
}
img {
height: 100%;
}
This will produce the following effect:
However, as you can see, the kitten is not central, but you can use Flex box to sort this out.
div {
width: 80px;
height: 80px;
border: 2px solid red;
justify-content: center;
display: flex;
flex-direction: row;
}
img {
flex: 1;
height: 100%;
}