Skip to content

Instantly share code, notes, and snippets.

@EtienneLem
Created September 12, 2013 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EtienneLem/6541666 to your computer and use it in GitHub Desktop.
Save EtienneLem/6541666 to your computer and use it in GitHub Desktop.
Responsive images container (Bonus: The content flow stays the same whether the image is loaded or not (or broken))
def image_container(path, width, height)
%(<div class="image-container" style="max-width: #{width}px">
<div style="padding-top: #{(height.to_f / width.to_f) * 100}%">
#{image_tag(path)}
</div>
</div>).html_safe
end
# Note: If you want the image to scale up, remove the `max-width`
<%= image_container('foo.png', 500, 400) %>
<!--
<div class="image-container" style="max-width: 500px">
<div style="padding-top: 80%">
<img src="/assets/foo.png" alt="Foo">
</div>
</div>
-->
/* Inline image? Sure */
/* .image-container { display: inline-block; width: 100% } */
/* Centered? Done */
/* .image-container { margin: auto } */
.image-container > div { position: relative }
.image-container img {
position: absolute;
top: 0; left: 0;
width: 100%; height: 100%;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment