Skip to content

Instantly share code, notes, and snippets.

@cladley
Created June 10, 2016 12:49
Show Gist options
  • Select an option

  • Save cladley/c452d4ed2963f6375e0d3c416985b839 to your computer and use it in GitHub Desktop.

Select an option

Save cladley/c452d4ed2963f6375e0d3c416985b839 to your computer and use it in GitHub Desktop.
snippet to create a full screen image on any viewport size
<div class="fullscreen" data-img-width="1500" data-img-height="900"> <---- because its a background image, we need the width and height
// whatever here. If it was a normal image tag, we could just get it off
</div> the image
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
.fullscreen {
width: 100%;
height: 100%;
background-image:url('http://someimage.jpg');
background-repeat: no-repeat;
background-position: 50% 50%;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var $window = $(window);
function backgroundResize() {
var windowHeight = $(window).height();
$('fullscreen').each(function(el) {
var $el = $(el);
var containerWidth = $el.width();
var containerHeight = $el.height();
var imageWidth = $el.data('data-img-width');
var imageHeight = $el.data('data-img-height');
var ratio = imageWidth / imageHeight;
imageHeight = containerHeight;
imageWidth = imageHeight * ratio;
if(containerWidth > imageWidth) {
imageWidth = containerWidth;
imageHeight = imageWidth / ratio;
}
$el.css('background-size', imageWidth + "px " + imageHeight + "px");
});
}
$window.resize(backgroundResize);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment