Web Development - Let CSS Position Background Images Exactly Where You Want Them: Part 1
If you've ever used CSS to display a background image, you probably know that you can also control whether the browser repeats the image. By default when you supply an image for a background, like so:
The browsers automatically repeat the image across the entire background. To turn this repetition off, you can use the
option. With this setting in place, the browser will only display the image once.
By default the browsers position the background image in the element's upper-left corner. But what if you want to place it elsewhere?
Fortunately, CSS offers the background-position property to do just that. With this property, you must supply two setting values: one that defines the image-s horizontal position, and one that defines the vertical position, along the lines of:
- background-position:x-pos, y-pos
The CSS spec offers you three ways to assign these positioning values. We'll cover the first one in this tip. And the remaining two in a follow-up
The quickest way to assign a position to a background image is to use a series of built-in positioning words: top, bottom, left, right, and center. Naturally you can use center to describe either vertical or horizontal positioning. Simply place them in the CSS declaration and separate them with a space. So, to place a background image in the center of an element, you might use the following:
- background-position:center center;
or to place it at the bottom right corner:
- background-position:bottom right