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

后端 未结 13 1041
难免孤独
难免孤独 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:21
    background: url(images/bg.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    
    0 讨论(0)
  • 2020-12-04 09:28

    image{

    background-size: cover;
      background-repeat: no-repeat;
      background-position: center;
      padding: 0 3em 0 3em; 
    margin: -1.5em -0.5em -0.5em -1em; 
      width: absolute;
      max-width: 100%; 
    
    0 讨论(0)
  • 2020-12-04 09:29
    <style>
        { margin: 0; padding: 0; }
    
        html { 
            background: url('images/yourimage.jpg') no-repeat center center fixed; 
            -webkit-background-size: cover;
            -moz-background-size: cover;
            -o-background-size: cover;
            background-size: cover;
        }
    </style>
    
    0 讨论(0)
  • 2020-12-04 09:30

    Not sure that stretching a background image is possible. If you find that it's not possible, or not reliable in all of your target browsers, you could try using a stretched img tag with z-index set lower, and position set to absolute so that other content appears on top of it.

    Let us know what you end up doing.

    Edit: What I suggested is basically what's in gabriel's link. So try that :)

    0 讨论(0)
  • 2020-12-04 09:34

    If you need to stretch your background image while resizing the screen and you don't need compatibility with older browser versions this will do the work:

    body {
        background-image: url('../images/image.jpg');
        background-repeat: no-repeat;
        background-size: cover;
    }
    
    0 讨论(0)
  • 2020-12-04 09:38

    The following code I use mostly for achieving the asked effect:

    body {
        background-image: url('../images/bg.jpg');
        background-repeat: no-repeat;
        background-size: 100%;
    }
    
    0 讨论(0)
提交回复
热议问题