HTML CSS – Resize a DIV Element to Its Background Image Size

backgroundcsshtml

Is it possible to make a <div> adapt to its background image? I mean to maintain the proportions width and height.

Clarification:

  • The div change the width. (it is a responsive design)

  • I do not mean to make the background adapt to the div. This is possible with background-size. But what I am asking is the way round: to have a image in the background and make the div parent adapt to that image whatever its size is.

  • I know that I can do something similar if I put the image in the html, and not in the background. But in this case, I could not change the image for different device sizes. So I am asking to put the image in background to be able to change it with CSS.

In the example I give, I can make the image adapt to the width but I get a gap with the height. Can I make the div adapt to the height too of the image , as the image changes its size? Asked in another way: In a responsive environment, can a div with an image background, change in size without leaving empty spaces ?

Here is the example to play.

CSS:

#image {
    margin:0px auto; 
    width:90%;
    max-width:512px;
    height:512px; /* I need to give heigt to make it visible? */

    background-image:url('http://www.w3.org/html/logo/downloads/HTML5_Logo_512.png');
    background-repeat:no-repeat;
    background-size:100%;
    background-color:yellow;/*just to make visible the gap in the height*/
}

HTML:

<div id="image"></div>

Best Answer

No it is NOT possible to adapt a div to it's background image.

Because it is 'senseless'

This is how:

A div's size is determined by its "content", or if its dimensions are SPECIFICALLY set. Since the background-image does not fall into any of these categories, you can see that it's impossible.

What you CAN do is this:

HTML

<div class="image-controlled">
  <img>...</img>
  <div class="content">...</div>
</div>

CSS

 .image-controlled {
   position: relative; 
   overflow: hidden <-- optional, if you want to cut off .content which overflows the image boundaries
 }
 .content {
   position: absolute;
   top: 0; left: 0; <-- position of the content as it should be (normally)
 }

The div will now be the size of the image, and the .content will be shown over it.


Also note that the .content div can come above or below the <img> in order of appearance, but the effect would be the same. But, if you apply a position property on the img element too, then you'll need to set the z-index of .content greater than that of <img>

Related Question