Stretch and scale CSS background

前端 未结 16 2008
难免孤独
难免孤独 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 02:42

    Scaling an image with CSS is not quite possible, but a similar effect can be achieved in the following manner, though.

    Use this markup:

    with the following CSS:

    #background {
        width: 100%; 
        height: 100%; 
        position: absolute; 
        left: 0px; 
        top: 0px; 
        z-index: 0;
    }
    
    .stretch {
        width:100%;
        height:100%;
    }
    

    and you should be done!

    In order to scale the image to be "full bleed" and maintain the aspect ratio, you can do this instead:

    .stretch { min-width:100%; min-height:100%; width:auto; height:auto; }
    

    It works out quite nicely! If one dimension is cropped, however, it will be cropped on only one side of the image, rather than being evenly cropped on both sides (and centered). I've tested it in Firefox, Webkit, and Internet Explorer 8.

提交回复
热议问题