I have a background image, it's 2500 px wide yellow on both sides of a white block that is 940px wide and in the centre. I want it to repeat up and down so repeat-y.

How can I set the CSS so the background image always appears centre regardless of the screen res viewed at.

2 answers

This was chosen as the best answer

Use the center keyword, like this:

background-position: center top; /* X-axis Y-axis */

When used in full shorthand version (background: [color] [image] [position] [repeat];) it looks somethink like this:

background: #f00 url(image.jpg) center 0 repeat-y;

A question, out of curiosity, why such a wide image? Couldn't you use a background color of yellow instead? (please comment on this answer to reply)

Answered over 8 years ago by Jens Hedqvist
  • "50%" will also work in place of "center" for x and y axis. "0" for "left" on the x-axis and for "top" on the y-axis. And "100%" for "right" on the x-axis and for "bottom" on the y-axis. ... so `background: #f00 url(image.jpg) repeat-y 50% 0;` is the same as above but slightly less bytes. Also the CSS spec lists the shorthand properties in this order: ([background-color] [background-image] [background-repeat] [background-attachment] [background-position]) which is why I tend to put the 'repeat' value before the 'position' values. Check out the spec here: http://www.w3.org/TR/CSS2/colors.html#background Andy Ford over 8 years ago

Great thanks, this works great. Yes I guess now I can center the background I can use background colour instead of such a wide image. Many thanks.

Answered over 8 years ago by Andrew Turner