Stretch and scale CSS background

前端 未结 16 2004
难免孤独
难免孤独 2020-11-22 02:28

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

相关标签:
16条回答
  • 2020-11-22 03:01

    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.

    0 讨论(0)
  • 2020-11-22 03:07

    Use the CSS 3 property background-size:

    #my_container {
        background-size: 100% auto; /* width and height, can be %, px or whatever. */
    }
    

    This is available for modern browsers, since 2012.

    0 讨论(0)
  • 2020-11-22 03:07

    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;
    }
    
    0 讨论(0)
  • 2020-11-22 03:09

    I would like to point out that this is equivalent to doing:

    html { width: 100%; height: 100%; }
    body { width: 100%; height: 100%; /* Add background image or gradient to stretch here. */}
    
    0 讨论(0)
提交回复
热议问题