Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css Image with fixed width and auto adjust height

Tags:

css

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?

like image 960
4 Leave Cover Avatar asked Oct 29 '25 17:10

4 Leave Cover


2 Answers

@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

like image 66
omukiguy Avatar answered Oct 31 '25 06:10

omukiguy


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>
like image 21
Nenad Vracar Avatar answered Oct 31 '25 07:10

Nenad Vracar