2

I have a fixed div with the css width: 400px; height: 280px; but my image comes from various dimension, some are portrait some landscape. How do I fit/stretch/fill my image regardless of source size into the div size?

4 Leave Cover
  • 1,248
  • 12
  • 40
  • 83

4 Answers4

4

@giorgi-parunov has the simplest and best method. owever if you want to use , I suggest that you use css to make the image responsive to the div.

img {
     max-width:100%;
     height: auto
}

You can also use object-fit: cover

omukiguy
  • 1,401
  • 3
  • 17
  • 36
3

If you have fixed size on div you can just set height/width of img to 100%.

div {
  width: 150px;
  height: 50px;
  border: 1px solid black;
}
img {
  width: 100%;
  height: 100%;
}
<div>
  <img src="http://cdn2.spectator.co.uk/files/2016/04/iStock_000069830477_Small.jpg">
</div>

If you want to fill div but you also want to keep image aspect ratio you can use object-fit: cover that is similar to background-size: cover when you use img as background.

div {
  width: 100px;
  height: 150px;
  border: 1px solid black;
}
img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div>
  <img src="http://cdn2.spectator.co.uk/files/2016/04/iStock_000069830477_Small.jpg">
</div>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1

I think the best way yo do it , do it with background-image.

HTML<div style="background-image: url("paper.gif"); background-size: cover; background-position: center;"></div>

It is the best way to add your image to the div without Javascript.

0

You can check this answer to fit any image in a container centered https://stackoverflow.com/a/36063374/2894798 In your case the code would be

 .container {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid;
  width: 400px; /*customize to your needs 100%*/
  height: 280px; /*customize to your needs*/
}
.container img
{
 max-width:100%;
 max-height:100%;
}

here is the fiddle

Community
  • 1
  • 1
Renzo Calla
  • 7,486
  • 2
  • 22
  • 37