I’ve written a web page where the content sits within a fixed-width, centered div, like so:
<div style='width:800px; margin: -5px auto 0px auto;' >
This is a fixed-width centered div!
</div>
Everything was fine until I was asked to put a background image within the div. Using CSS-background inevitable results in the image being stretched or tiled. I don’t want that. I want one instance of the image with it’s upper left-hand corner in the upper left-hand corner of my fixed width div.
I tried to do this several ways.
Here’s the first way that doesn’t work:
<img src='images/background.jpg' alt='background'
style='position:relative;left:0;top:0;z-index:-1' />
In this example, the image is positioned exactly as I want, but the text of the div appears below the image.
Here’s the second way that doesn’t work:
<img src='images/background.jpg' alt='background'
style='position:absolute;left:0;top:0;z-index:-1' />
Using absolute positioning, the text appears over the image as I want. However, the image is now in the upper left-hand corner of the page. This is to be expected because there is no other element with absolute positioning. I understand that the solution should be to set the position of the fixed-width centered div to absolute as well. However, when I do this, my fixed-width div is no longer centered:
My div is no longer centered!
How can I write my HTML and CSS so that I have text within a fixed-width, centered div with a background image behind the text?
Yes, background-images repeat –by default. However, you can explicitly set background-repeat to
no-repeat[Edit] Vertical clipping can be resolved by setting your div’s min-height to the image’s pixel-height. This will ensure that your div is always at least as tall as your image. This is the ideal solution.
However, if your image is conceivably wider than your div’s 800px static width, you’ll need to go back to the nested image solution… Make the div
position:relativeand the imageposition:absoluteand the image’s top/left will be relative to the div rather than the page. In combination with a z-index-1on the image, you should be good to go (fiddle demonstrating an un-clipped image)