With CSS, how do I make an image span the full width of the page as a background image?

前端 未结 3 2001
独厮守ぢ
独厮守ぢ 2021-01-12 13:34

Say, like in this example here: http://www.electrictoolbox.com/examples/wide-background-image.html

When I do it, I end up getting white borders around the image no m

相关标签:
3条回答
  • 2021-01-12 14:06

    You set the CSS to :

    #elementID {
        background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) center no-repeat;
        height: 200px;
    }
    

    It centers the image, but does not scale it.

    FIDDLE

    In newer browsers you can use the background-size property and do:

    #elementID {
        height: 200px; 
        width: 100%;
        background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) no-repeat;
        background-size: 100% 100%;
    }
    

    FIDDLE

    Other than that, a regular image is one way to do it, but then it's not really a background image.

    0 讨论(0)
  • 2021-01-12 14:11

    Background images, ideally, are always done with CSS. All other images are done with html. This will span the whole background of your site.

    body {
      background: url('../images/cat.ong');
      background-size: cover;
      background-position: center;
      background-attachment: fixed;
    }
    
    0 讨论(0)
  • 2021-01-12 14:13

    If you're hoping to use background-image: url(...);, I don't think you can. However, if you want to play with layering, you can do something like this:

    <img class="bg" src="..." />
    

    And then some CSS:

    .bg
    {
      width: 100%;
      z-index: 0;
    }
    

    You can now layer content above the stretched image by playing with z-indexes and such. One quick note, the image can't be contained in any other elements for the width: 100%; to apply to the whole page.

    Here's a quick demo if you can't rely on background-size: http://jsfiddle.net/bB3Uc/

    0 讨论(0)
提交回复
热议问题