Skip to content

Instantly share code, notes, and snippets.

@emilbayes
Created February 16, 2014 10:36
Show Gist options
  • Save emilbayes/9032254 to your computer and use it in GitHub Desktop.
Save emilbayes/9032254 to your computer and use it in GitHub Desktop.
Make one element cover another proportionately
(function($) {
$.fn.extend({
coverElement: function(options) {
var settings = $.extend(true, {
container: 'html' //Default is fit the viewport
}, options);
var $elements = this,
$container = this.first().closest(settings.container);
function applyCover() {
$elements.each(function() {
var $img = $(this);
var windowheight = $container.height(),
windowwidth = $container.width(),
imageheight = $img.height(),
imagewidth = $img.width();
var widthratio = windowwidth/imagewidth,
heightratio = windowheight/imageheight;
console.log(imagewidth, imageheight, $container);
if(widthratio < heightratio) { //Too high/small
$img.height(windowheight) //Fill height
.width(imagewidth * heightratio) //Scale proportinately
.css('left', ($img.width() - windowwidth) / -2) //Pull left by half of overflow
.css('top', 0); //Reset from possible previous scaling
}
else if(widthratio > heightratio) { //Too wide/narrow
$img.width(windowwidth) //Fill width
.height(imageheight * widthratio) //Scale proportinately
.css('top', ($img.height() - windowheight) / -2) //Pull up by half of overflow
.css('left', 0); //Reset from possible previous scaling
}
else { //Fits exactly
$img.width(windowwidth);
$img.height(windowheight);
}
});
}
applyCover();
$(window).resize(applyCover); //Could be throttled
}
});
})(jQuery);
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="container">
<img src="http://phaseoneimageprofessor.files.wordpress.com/2013/07/iqpw29_main_image_.jpg" alt="">
</div>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="coverElement.js"></script>
<script>
$(window).load(function() {
$container = $('.container'); //$('html'); //Use html to fit in viewport
$img = $container.find('img');
$img.coverElement({
container: $container //Can be element, jQuery object or selector
});
});
</script>
</body>
</html>
html, body {
width: 100%; height: 100%;
margin: 0; padding: 0;
}
.container {
position:relative;
width: 480px;
height: 530px; /* widthratio > heightratio == true. For opposite:; 230px */
background:steelblue; /* For debugging */
}
img {
position: absolute;
opacity: 0.5; /* For debugging */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment