Proportional scaling background image and enclosing div container.
This script is based on the window width. It scaled according to the width of the window the width and height of a div container and used background image. It scale In dependence of the size of the background image which is used for the div container.
HTML
<link rel="stylesheet" href="http://scurrilus.de/scurrilus-jsfiddle/scurrilus-copyright.css">
<script src="http://scurrilus.de/scurrilus-jsfiddle/scurrilus-copyright.js"></script>
<!--powered by SCURRILUS-->
<div id="scurrilusCopy"></div>
<script>scurrilusCopy();</script>
<!--ende powered by SCURRILUS-->
<div class="code">
<div class="content">This image is a background image. <br/>The background image and the div container size change <br/>proportional depending on the width of the window.<br/><br/>
<div class="values"></div>
</div>
<script>
$(document).ready(function() {
<!-- Call function first -->
resizeBackgroundImage();
<!-- Eventlistener get width of window and call function resizeBackgroundImage(); -->
window.addEventListener("resize", function() {
resizeBackgroundImage();
} , true);
});
</script>
</div>
CSS
.content {
/*The div height always depends on the dimensions of the background image.*/
/*Background Image 1920x1200*/
/* background: url('http://wallpaper-fullhd.com/wp-content/uploads/2013/03/at-the-beach-hd-wallpaper-1920x1200.jpg') !important;*/
/*Background Image 960Ă—854*/
background: url('http://placehold.it/940x456') !important;
border: 2px solid #000000;
display: block;
height: 300px;
color: #fff;
text-align: center;
box-sizing: border-box;
padding-top: 15%;
font-size: 12px;
text-shadow: 1px 1px 0 #333;
}
JavaScript
function resizeBackgroundImage() {
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
var imageUrl = $('.content').css('background-image'), image;
// Remove url()
imageUrl = imageUrl.match(/^url\("?(.+?)"?\)$/);
if (imageUrl[1]) {
imageUrl = imageUrl[1];
image = new Image();
// If it is not already loaded
$(image).load(function () {
var newImageWidth = width + "px ";
var divheight = width*image.height/image.width;
var newImageHeight = Math.round(divheight) + "px ";
// console.log(image.width + 'x' + image.height);
// console.log(newImageWidth + "x " + newImageHeight);
// Do something with width and height values
/*$('.content').attr('style', 'background-size: ' + newImageWidth + newImageHeight + '!important');*/
$('.content').css('height', newImageHeight);
$('.content').css('widtgh', newImageWidth);
// Value output on screen
var valueText = "original image size: "+ image.width +"x" + image.height + "<br/>" + "new image size: "+ width +"x" + Math.round(divheight);
$('.values').html(valueText)
});
image.src = imageUrl;
}
}