Reputation: 16615
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.
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
Upvotes: 3
Views: 9921
Reputation: 3578
You can manage this with absolute positioning too, to make it behave more like cover. An example fiddle
Position absolute with left: 0 and right: 0 with margin: auto centres the image horizontally. Setting the container's overflow to hidden means that it will not expand past the edges of the container.
Fiddle code;
<div class="container">
<img src="http://www.online-image-editor.com//styles/2014/images/example_image.png" alt="">
</div>
.container{
width: 25%;
height: 200px;
overflow: hidden;
position: relative;
}
.container img{
position: absolute;
right: 0; left: 0;
margin: auto
}
Upvotes: 0
Reputation: 10019
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/
Upvotes: 5