Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

html - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

jsBin demo

<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?

jsBin demo 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%;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...