Skip to content

Instantly share code, notes, and snippets.

@droid001
Created October 14, 2015 07:16
Show Gist options
  • Save droid001/3fb1962835ce2567fb97 to your computer and use it in GitHub Desktop.
Save droid001/3fb1962835ce2567fb97 to your computer and use it in GitHub Desktop.
Make inline img's cover container
// From http://paulbrowne.fi/2015/01/31/background-image-properties-inline-images
<div class="icovr">
<img href="some-image.jpg" alt="" >
</div>
<script>
function imgcover(){
// target all images in this container
$(".icovr").each(function(){
var c = $(this).width(),
d = $(this).height(),
// aspect ratio of container
y = c/d,
e = $(this).children("img")[0].naturalWidth,
f = $(this).children("img")[0].naturalHeight,
// aspect ratio of image (at natural dimensions)
z = e/f;
// if the image's aspect ratio is less than that of the container,
// then use width:100% so that the image fills vertically
if (z<=y) {
$(this).children("img").css({
"position" : "relative",
"width" : "100%",
"height": "auto",
// then center the image horizontally
"top" : (d-(f/(e/c)))/2 + "px",
"left" : 0
})
}
if (z>y) {
// if the image's aspect ratio is greater than that of the container,
// then use width:100% so that the image fills horizontally
$(this).children("img").css({
"position" : "relative",
"width" : "auto",
"height": "100%",
// then center the image vertically
"left" : (c-(e/(f/d)))/2 + "px",
"top" : 0
})
}
})
}
// call on load and resize events
window.addEventListener("resize", imgcover);
window.addEventListener("load", imgcover);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment