Updated Answer
Testing the old answer
During testing I found out that the old approach (creating an image element on the fly to get its dimensions) only works on latest versions of Chrome, Safari and Firefox but not IE. Thus it's not a cross browser method.
What the OP really wants
In addition, as per the OP's comments below, I figured it out that the OP wants the <main>
element to be 70%
of height of the browser. But Once the width of the <main>
element reaches the edges of the background image by resizing the window horizontally, the height <main>
element should be reduced to remove the vertical gap between the background image.
(That vertical gap happens because of using contain
value for the background image to keep the image inside of the box and keeping the aspect ratio).
Considering that, and our failure to get the dimensions of the background image on-the-fly with a large scale of web browsers, you'll end up with the following:
var main = $('#main'),
imgwidth = 500, // Set the width/height of the background image manually
imgHeight = 300,
imgRatio = imgHeight/imgwidth,
mainHeight = main.height();
$(window).resize(function() {
var mainWidth = main.width(),
mainRatio = mainHeight/mainWidth;
// Compare ratio of the <main> element and the background image
if (mainRatio >= imgRatio) {
main.height(imgRatio * mainWidth);
} else {
main.height('70%');
}
}).resize(); // Trigger the handler once the script is loaded
The old Answer (Under a misconception)
There's no pure CSS way to resize an element's dimensions according to its background-image.
You'll need to use JavaScript to achieve that. By using JavaScript we get the computed background-image
and create an image element (using the background image) on the fly to get the dimensions of the background image
Here you go:
<div class="wrap">
<main id="main"></main>
<div>another div</div>
</div>
I've combined two #main
and <main>
elements to condense the markup in this particulat instance.
jQuery version:
var
main = $('#main'),
imgSrc = main.css('background-image').slice(4, -1);
$('<img />')
.attr('src', imgSrc)
.on('load', function() {
main.height(this.height);
});