Skip to content

Instantly share code, notes, and snippets.

@kontur
Created March 4, 2014 10:56
Show Gist options
  • Save kontur/9344293 to your computer and use it in GitHub Desktop.
Save kontur/9344293 to your computer and use it in GitHub Desktop.
jQuery make nested element (img / video) cover the container area with debounced resize listener
$(function () {
var resizeTimer;
$(window).resize(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(onResize, 50);
});
onResize();
function onResize() {
var $container = $("#container"),
$content = $("#content"),
containerRatio = $container.width() / $container.height(),
contentRatio = $content.width() / $content.height()
if (containerRatio < contentRatio) {
$content.css({
marginLeft: -($content.height() * contentRatio - $container.width()) / 2,
marginTop: "auto",
height: "100%",
width: "auto"
});
} else {
$content.css({
marginLeft: "auto",
marginTop: -($content.width() / contentRatio - $container.height()) / 2,
height: "auto",
width: "100%"
});
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment