Sunday, February 13, 2011

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

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 have to do it some other way besides it being a background image?

My current css is:

body {
    background-position: left top;
    background-image: url(_images/home.jpg);
    background-repeat: no-repeat;
}

Thanks in advance.

Edit: I'm not keen on maintaining the CSS in Gabriel's suggestion so I'm changing the layout of the page instead. But that seems like the best answer so I'm marking it as such.

  • You're pretty much out of luck there, sorry.

    From Sciolist
  • I did a quick google search and found this link:

    http://www.htmlite.com/faq022.php

    fung : Was trying to avoid stuff like this which seem more like a CSS hack. Will upvote anyway.
  • 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 :)

    eyelidlessness : I saw this technique in action at least a decade ago. I can't imagine it wouldn't still work now.
  • You cannot in pure CSS. Having an image covering the whole page behind all other components is probably your best bet (looks like that's the solution given above). Anyway, chances are it will look awful anyway. I would try either an image big enough to cover most screen resolutions (say up to 1600x1200, above it is scarcer), to limit the width of the page, or just to use an image that tile.

    From PhiLho
  • To expand on @PhiLho answer, you can center a very large image (or any size image) on a page with:

    { 
    background-image: url(_images/home.jpg);
    background-repeat:no-repeat;
    background-position:center; 
    }
    

    Or you could use a smaller image with a background color that matches the background of the image (if it is a solid color). This may or may not suit your purposes.

    { 
    background-color: green;
    background-image: url(_images/home.jpg);
    background-repeat:no-repeat;
    background-position:center; 
    }
    
    From Traingamer
  • http://www.w3.org/TR/css3-background/#the-background-size

    From porneL

0 comments:

Post a Comment