4 Leave Cover
4 Leave Cover

Reputation: 1276

css Image with fixed width and auto adjust height

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?

Upvotes: 3

Views: 19949

Answers (4)

omukiguy
omukiguy

Reputation: 1437

@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

Upvotes: 5

Nenad Vracar
Nenad Vracar

Reputation: 122047

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>

Upvotes: 3

Renzo Calla
Renzo Calla

Reputation: 7696

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

Upvotes: 0

Giorgi Parunov
Giorgi Parunov

Reputation: 71

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.

Upvotes: 1

Related Questions