Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Responsive Image inside a div

Well, i have a div with 50% width and 200px height, there is an image inside this div that i want to make it responsive in all resolution. if i put this image on div's background image and give it background-size: cover and responsive output exactly similar what i want. but the problem is i can't to put this image on background image, and should be a <img/> element.

enter image description here

so i made a example on JSFiddle to clear my question.

after run this example please change preview section width to see responsive output. ok, top image has a <img/> inside that div, bottom image is background image. i want exactly responsive output of bottom div that made with background-image, in other hand the question is: how can make an image responsive like background-size: cover in a div.

#DivWithImg {
  width: 50%;
  height: 200px;
  background: red;
  margin: 0 5px 0 5px;
  overflow: hidden;
  border: 1px solid black;
}

#DivWithImg img {
  width: 100%;
  height: 100%;
}

#DivWithBGImg {
  width: 50%;
  height: 200px;
  background: red url('http://img.huffingtonpost.com/asset/scalefit_600_noupscale/56328113190000a600b9540d.jpeg');
  margin: 0 5px 0 5px;
  background-size: cover;
  border: 1px solid black;
}
<!-- Div With Image -->

<div id="DivWithImg">
<img src="http://img.huffingtonpost.com/asset/scalefit_600_noupscale/56328113190000a600b9540d.jpeg"/>
</div>
<br>
<!-- Div With Background Image -->

<div id="DivWithBGImg">
</div>

Thanks in advance

like image 434
Pedram Avatar asked Jun 09 '26 18:06

Pedram


1 Answers

you can make the height auto for the image, it should resize accordingly. Or you can just omit the height property, it's set to auto by default if you don't give it a value

https://jsfiddle.net/ahmadabdul3/4njw64s0/1/

update:

you can set a min-height/width so the image can do what you want. basically set the minimum height to 100% so it never get smaller height-wise. and then set the min-width to the width of the actual image, so it doesn't ever get smaller than that.

https://jsfiddle.net/ahmadabdul3/4njw64s0/4/

like image 103
duxfox-- Avatar answered Jun 11 '26 09:06

duxfox--