CSS: Scale background image down if larger than window, keep at 100% otherwise

后端 未结 4 2045
灰色年华
灰色年华 2021-01-12 09:08

I\'d like to deploy a background image in the body of my website that scales down with the window resolution, but does not scale up beyond it\'s original size (1920x1080). T

4条回答
  •  离开以前
    2021-01-12 09:45

    You could try creating an html tag with a specific id

    e.g.

    HTML

    never forget the blind folks!
    

    CSS

    img#mybg {
        position: fixed; //image will always be top: 0 left: 0 by default.
        display: block; //make it a block for width to work.
        width: 100%; //set default width
        height: 100%; //set default height
        max-width: 1920px; //set max width
        max-height: 1080px; //set max height
        z-index: -999999; //set z-index so it won't overlap any other element.
    }
    

    For dynamic centering you would have to use Javascript in combination with a window.onresize event.

    If you need more information I will edit my post accordingly.

    A good alternative which is very easy to use(but does stretch your background) would be to use jquery backstretch plugin. It allows you to simply add a fullscreen background image, which will scale with resolution (which is not exactly what you want, but the best alternative I could think of).

提交回复
热议问题