Pergunta

So, here the background-size of <main> element is contain, which cause it's container #main contains the space towards the bottom on lower screen sizes.

So, I wanted to resize the height of #main responsively according to <main>'s background-image height to remove the vertical gap in lower screen sizes.

Note that the background image shouldn't be stretched or hidden.

HTML

<div id="main">
    <main>

    </main>
</div>

CSS

#main{
    width: 100%;
    height: 70%;
}
main{
    max-width: 100%;
    height: 100%;
    background: url(images/img-main.png) no-repeat top center;
    background-size: contain;
}

JavaScript

var toHeight = $('main')//?????? I'm stacked here 
$('#main').css('height',toHeight);

Any ideas?


Here's the jsfiddle demo (resize the window to understand)

+--------------------------+--------
|                          |
|    background-image      |
|              height      |       main
|                          |
|                          |      height
+--------------------------+
|         vertical         |
|           gap            |
+--------------------------+---------

Should be converted to:

+--------------------------+--------
|                          |       main
|    background-image      |
|              height      |     height
|                          |
|                          | 
+--------------------------+----------
Foi útil?

Solução

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

WORKING DEMO.


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);
    });

WORKING DEMO.

Outras dicas

You can do this by simply using an <img> tag instead of the background-image attribute:

HTML

<div class="wrap">
    <div id="main">
        <img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRqHMio3jll2W62WXJHbufc-xxYPxec_ip8Ez0lQv2P7Umy2kPKrw">
    </div>
    <div>another div</div>
</div>

CSS

#main{
    width: 100%;
    height: auto;
    border: 1px solid red;
    text-align: center;
}

img{
    max-width: 100%;
    vertical-align: middle; //prevents a default bottom margin from appearing
}

Fiddle: http://jsfiddle.net/wAJyv/6/ (try resizing)

Edit: Alternatively, if you want the image to be scaled upwards too incase the main div is wider, you can simply use width: 100% instead of max-width: 100%: http://jsfiddle.net/wAJyv/7/

give background-size: 100% 100%; in the css of .main than contain.

.main {
    background-size: 100% 100%;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top