Thursday, 21 June 2012

How to change background image position by using CSS

You can specify a position for background images. For that the CSS property background-position is used. This property takes the following values:

top left
top center
top right
center left
center center
center right
bottom left
bottom center
bottom right

But you can also use pixels with X and Y values. It's also possible to use a page percentage. As a practical example, suppose you wanted a logo in the top right of your page. You could do it like this:

BODY {

background-image: url('backgrounds/logo_brolly.gif');
background-position: top right;
background-repeat: no-repeat;

}

The effect would be this:

An image positioned using the CSS property background-position

Notice that we've used background-repeat with a value of no-repeat, otherwise we'd get a page full of brollies!

Here are some examples of the other values you can use:

background-position: 300px 100px;

background-position: 80% 0%;

With the pixel values (px) the X direction comes first, followed by the Y direction. A space separates the two. The same is true of the percentage values: X direction first, then Y direction, a space as the separator.

Try them out for yourself.

No comments:

Post a Comment