Last Updated: February 25, 2016
·
1.354K
· amoniker

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!

4 Responses
Add your response

Cool idea!

over 1 year ago ·

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 ·

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 ·

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

over 1 year ago ·