j0kp5q
Last Updated: February 25, 2016
·
916
· amoniker
Avatar closeup

Responsive Images with this One Weird Trick

I stumbled upon this method recently after some trial-and-error while creating a site that has a full-width, responsive layout.

I wanted various images on the site to:

  • take up 100% of the width of their parent
  • scale up using the image's correct aspect ratio
  • scale down to a reasonable size with a background-size:cover effect.

It's easier to show than tell, so take a look at the demo here: http://codepen.io/aMoniker/pen/bCtfv

Resize the rendered window and you'll get a feel for how it works.

The essence of the trick is that a container element (.flex-image) wraps a real <img>. The container sets its background-image to the same source as the <img> and gets a background-size:cover;. Then, the <img> is made invisible via visibility:hidden;

So, what you really see is the background image, while the invisible <img> element stretches the .flex-image container to the appropriate dimensions as it's scaled up. When it's scaled down, the (optional) min-height on the flex container gives you the benefit of a background-size:cover; effect.

You can use this in combination with other panels to create nice, flexible effects for your responsive pages. Like this: http://codepen.io/aMoniker/pen/zwgCp

¡que disfrutes!

Say Thanks
Respond

4 Responses
Add your response

17154
Kevinsimpergrey.smaller

Cool idea!

over 1 year ago ·
17200
Logo normal

This works great indeed. Additionally you can give the img-element a max-height or -width. This may come in handy when you display a gallery yet some images are extraordinary wide or tall. This way you can put a limit on the aspect ratio.

over 1 year ago ·
18045
21082009265 normal

Hey there is a solution without the image, you can do it the following way,

< div class="flex-image" >< / div > <br/>
<br/>
.flex-image {<br/>
width: 100%;<br/>
height: 0;<br/>
min-height: 300px;<br/>
box-sizing: border-box;<br/>
padding-bottom: 50%; /* image ratio */<br/>
background-image: url('http://apod.nasa.gov/apod/image/1410/mwSunToMoon_lane_1800.jpg');<br/>
background-size: cover;<br/>
background-position: center;<br/>
}

This way you exclude the img element. this works well for your example as well.<br/>

over 1 year ago ·
18056
Avatar closeup

Hey @costea_90, that sounds interesting - would you mind posting a codepen/jsfiddle demonstrating your method?

over 1 year ago ·