Tim Wilkinson
Tim Wilkinson

Reputation: 3801

Keep oversized background image centered

I am building a single page site constructed of 4 divs, one on top of the other and each one with its own fixed background image. The images are much wider than the screen as I want to site to keep its look across a large range of screen sizes, however does anyone know how to truely center a background image. So in a small monitor they would be viewing the center of the image, and in a larger monitor they would see the same place of the image, just with more around it. Just like this site has

http://www.cantilever-chippy.co.uk/

When the window is resized the background image moves accordingly.

Many Thanks.

Upvotes: 4

Views: 21382

Answers (3)

Sam
Sam

Reputation: 2747

If you check the css from your link you see the solution:

#images #bg_1 {
  background-image: url(images/bg/1.jpg);
  background-position: 50% 0;
}

And the div:

<div class="bg_block" id="bg_1" style="height: 1200px; width: 1055px;"></div>

By JavaScript they change the width of #bg_1 on every resize.

window.onresize = function(event) {
    $("#bg_1").css("width", $(window).width());
}

Upvotes: 20

hobberwickey
hobberwickey

Reputation: 6414

This should work

#bg{ 
   background-image:url(yourURL);
   background-repeat:no-repeat;
   background-attachment:fixed;
   background-position:center; 
}

The background-fixed property is for Firefox and Opera.

Upvotes: 9

GSP
GSP

Reputation: 3789

You're looking for the background-position CSS property.

http://www.w3schools.com/cssref/pr_background-position.asp

It can take an absolute offset in pixels (so if you know the size of your image and the size of the div you could calculate exactly where you want it to appear). Or, you can pass in a percentage. It can also take a negative numbers so you can offset it off the screen in any direction.

For your case, though, you probably want the simple "center" value. Something like this should work:

/* This should center the background image in the div. */
div.background_image_block {  
  background-position: center center;
}

Upvotes: 2

Related Questions