tonyf
tonyf

Reputation: 35539

How to set a background image centred in my website?

I have a query based on the following CSS and HTML code (see below).

I have a background image that spans the whole browser page (left to right), which is not what I'm after.

How can I get the background image to stay within the boundaries of my main content canvas, i.e. centered 850x600px and anything outside just be white?

    body {
background-color: #ffffff;
margin:0px;
padding:0px;
background-image: url(images/background.jpg);
background-repeat: repeat-x;
background-attachment: scroll;
}

#main {

width:850px;
margin: 0px auto 0px auto;
border: 0px solid #f0f0f0;

}

<body>

<div id="main">
<img src="images/female_model.jpg" id="female_model" alt="" />
<div id="colwrap1">
<img src="images/nav_bar.jpg" id="nav_bar" alt="" />
<img src="images/site_name.jpg" id="site_name" alt="" />
</div>
</div>

</body>

Upvotes: 1

Views: 349

Answers (3)

Dominic Cooney
Dominic Cooney

Reputation: 6535

If you want to attach the background to the main DIV, then specify the background there. It sounds like you want the background to be centered horizontally (background-position: 50%;) but repeat for the vertical extent of the main DIV (background-repeat: repeat-y;).

body {
  background-color: white;
  margin: 0px;
  padding: 0px;
}

#main {
  background-image: url(images/background.jpg);
  background-repeat: repeat-y;
  background-position: 50%;

  // rest as before ...
  width: 850px;
  ...
}

<div id="main">
   Lorem ipsum dolor sit amet, ...

If your background image does not appear it could be because the image is inaccessible or the main DIV has no height--that could happen if female_model and colwrap1 both float.

Upvotes: 3

noobzilla
noobzilla

Reputation: 1155

Dominic is correct. Move the background properties from body to the main div and you should have what you need.


If I have understood your question correctly, you want to set the page background to white and have the background of your main div be whatever image you set it to - correct?

If so, setting body to:

body
{
  background:#fff;
}

should do the trick.

Now, I also noticed that the image you want to use has a smaller width than your div. So you will want main to have the following properties:

#main
{
   background-image:url(myimage.jpg);
   background-position:top;
   background-repeat:repeat-x; <!-- you need this as your image is < than the div width -->
 }

That should do the trick. If it still doesnt work, perhaps you want to share the page link on your server. Its possible that we have misunderstood your question.

Upvotes: 0

Gareth
Gareth

Reputation: 138012

How about you just put the background image on your #main?

Upvotes: 1

Related Questions