Stretch and scale CSS background

2018-12-31 04:37发布

Is there a way to get a background in CSS to stretch or scale to fill its container?

标签: html css
16条回答
弹指情弦暗扣
2楼-- · 2018-12-31 04:47

Use the background-size attribute in CSS3:

.class {
     background-image: url(bg.gif);
     background-size: 100%;
}

EDIT: Modernizr supports detection of background-size support. You can use a JavaScript workaround written to work however you need it and load it dynamically when there is no support. This will keep the code maintainable without resorting to intrusive CSS hacks for certain browsers.

Personally I use a script to deal with it using jQuery, its an adaption of imgsizer. As most designs I do now use width %'s for fluid layouts across devices there is a slight adaptation to one of the loops (accounting for sizes that aren't always 100%):

for (var i = 0; i < images.length; i++) {
    var image = images[i],
        width = String(image.currentStyle.width);

    if (width.indexOf('%') == -1) {
        continue;
    }

    image.origWidth = image.offsetWidth;
    image.origHeight = image.offsetHeight;

    imgCache.push(image);
    c.ieAlpha(image);
    image.style.width = width;
}

EDIT: You may also be interested in jQuery CSS3 Finaliz[s]e.

查看更多
墨雨无痕
3楼-- · 2018-12-31 04:48

For modern browsers, you can accomplish this by using background-size:

body {
    background-image: url(bg.jpg);
    background-size: cover;
}

cover means stretching the image either vertically or horizontally so it never tiles/repeats.

That would work for Safari 3 (or later), Chrome, Opera 10+, Firefox 3.6+, and Internet Explorer 9 (or later).

For it to work with lower verions of Internet Explorer, try these CSS:

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";
查看更多
柔情千种
4楼-- · 2018-12-31 04:49

An additional tip for SolidSmile's cheat is to scale (the proportionate re-sizing) by setting a width and using auto for height.

Ex:

#background {
    width: 500px;
    height: auto;
    position: absolute; 
    left: 0px; 
    top: 0px; 
    z-index: 0;
}
查看更多
素衣白纱
5楼-- · 2018-12-31 04:49

Use the border-image : yourimage property to set your image and scale it upto the entire border of your screen or window .

查看更多
荒废的爱情
6楼-- · 2018-12-31 04:50

Add a background-attachment line:

#background {
    background-attachment:fixed;
    width: 100%; 
    height: 100%; 
    position: absolute; 
    margin-left: 0px; 
    margin-top: 0px; 
    z-index: 0;
}

.stretch {
    width:100%;
    height:auto;
}
查看更多
像晚风撩人
7楼-- · 2018-12-31 04:51

Another great solution for this is Srobbin's Backstretch which can be applied to the body or any element on the page - http://srobbin.com/jquery-plugins/backstretch/

查看更多
登录 后发表回答