How do I stretch a background image to cover the entire HTML element?

后端 未结 13 1042
难免孤独
难免孤独 2020-12-04 09:02

I\'m trying to get a background image of a HTML element (body, div, etc.) to stretch its entire width and height.

Not having much luck. Is it even possible or do I h

相关标签:
13条回答
  • 2020-12-04 09:41

    If you have a large landscape image, this example here resizes the background in portrait mode, so that it displays on top, leaving blank on the bottom:

    html, body {
        margin: 0;
        padding: 0;
        min-height: 100%;
    }
    
    body {
        background-image: url('myimage.jpg');
        background-position-x: center;
        background-position-y: bottom;
        background-repeat: no-repeat;
        background-attachment: scroll;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
    }
    
    @media screen and (orientation:portrait) {
        body {
            background-position-y: top;
            -webkit-background-size: contain;
            -moz-background-size: contain;
            -o-background-size: contain;
            background-size: contain;
        }
    }
    
    0 讨论(0)
提交回复
热议问题