简体   繁体   中英

background-size: cover on divs instead of background

I have a number of divs of certain, knows sizes. The pictures that I would like to use as background differ in size so, I was thinking to use background-size:cover to make sure that the images inside sort of look good instead of being stretched or shown just a part of them.

But I cannot find the way to accomplish this. Another reason why this is not working is that I have the need to assign the background-image property inline only.

Does anyone have any idea on how to use background-size:cover on something that is actually not the whole viewport, but just a div?

Thanks in advance

Try these styles:

background-size:contain;
background-repeat:no-repeat;
background-position:50% 50%;

Add a class with the following attributes, use this class with that div and make sure that for maintaining the aspect ratio you make width and height to 100% inside another div positioned relative

background: url(images/bg.jpg) no-repeat center center fixed; 
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;

Edit:

Resize the frames in jsfiddle and you will observe that the image does not shrink below the min-width (set in percentages) while it can expand depending upon the space available

http://jsfiddle.net/UQP78/12/

http://jsfiddle.net/UQP78/10/

<div id="bg">
    <img src="http://www.faber04blog.com/wp-content/uploads/2012/08/jquery" alt="">
</div>

#bg {
    position:fixed; 
    top:-50%; 
    left:-50%; 
    width:150%; 
    height:150%;
}
#bg img {
    position:absolute; 
    top:0; 
    left:0; 
    right:0; 
    bottom:0; 
    margin:auto; 
    min-width:25%;
    min-height:25%;
}

http://jsfiddle.net/UQP78/7/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM