htmlcss

Scale div to fit background image


I have a div with a background image that I want to expand 100% width and auto scale the div to fit the required height of the image. At the moment it is not scaling the div height unless I set the height of the div to 100% but then it just stretches to the full height of the screen, whereas I want it to scale to the height of the image.

Here is the html:

<div id="mainHeaderWrapper">


</div><!--end mainHeaderWrapper-->
<br class="clear" />;

Here is the css:

    #mainHeaderWrapper{


     background: url(http://localhost/site/gallery/bg1.jpg);
     width: 100%;
     height: auto;
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover; 
     background-size: 100% 100%;

     background-repeat: no-repeat;
     background-position: center center; 

 }

 .clear { clear: both; }

Thanks for any and all help


Solution

  • Let a transparent image dictate the DIV dimensions.
    Inside that div put the same image with CSS opacity: 0

    <div id="mainHeaderWrapper">
       <img src="path/to/image.jpg"><!-- I'm invisible! -->
    </div>
    

    set that image to

    #mainHeaderWrapper {
        background: no-repeat url(path/to/image.jpg) 50% / 100%;
    }
    #mainHeaderWrapper img {
        vertical-align: top;
        width: 100%; /* max width */
        opacity: 0;  /* make it transparent */
    }
    

    That way the height of the DIV will be dictated by the containing invisible image, and having the background-image set to center, full (50% / 100%) it will match that image's proportions.

    Need some content inside that DIV?

    Due to the containing image, you'll need an extra child element that will be set to position: absolute acting as an overlay element

    <div id="mainHeaderWrapper">
       <img src="path/to/image.jpg"><!-- I'm invisible! -->
       <div>Some content...</div>
    </div>
    
    #mainHeaderWrapper{
        position: relative;
        background: no-repeat url(path/to/image.jpg) 50% / 100%;
    }
    #mainHeaderWrapper > img{
        vertical-align: top;
        width: 100%; /* max width */
        opacity: 0;  /* make it transparent */
    }
    #mainHeaderWrapper > div{
        position: absolute;
        top: 0;
        width: 100%;
        height: 100%;
    }