Stretch and scale a CSS image in the background - with CSS only

后端 未结 22 2668
迷失自我
迷失自我 2020-11-22 01:37

I want that my background image stretch and scale depending on the browser viewport size.

I\'ve seen some questions on Stack Overflow that do the job, like

22条回答
  •  半阙折子戏
    2020-11-22 02:03

    Using the code I mentioned...

    HTML

    CSS

    #background {
        width: 100%; 
        height: 100%; 
        position: fixed; 
        left: 0px; 
        top: 0px; 
        z-index: -1; /* Ensure div tag stays behind content; -999 might work, too. */
    }
    
    .stretch {
        width:100%;
        height:100%;
    }
    

    That produces the desired effect: only the content will scroll, not the background.

    The background image resizes to the browser viewport for any screen size. When the content doesn't fit the browser viewport, and the user needs to scroll the page, the background image remains fixed in the viewport while the content scrolls.

    With CSS 3 it seems this would be a lot easier.

提交回复
热议问题