CSS Background Color and Image

CSS background color

We can also use the <body> tag to adjust some of the most basic properties of our web pages, such as changing the background color or image of the page:

body {
	background-color: green;
	}

The background-color CSS property can be used to change the color that appears behind all the other elements on our web page. Think of it like the canvas color - it is the starting point for our website, but we can cover it up by adding elements on top. Background colors are a great way to give our site a more personalized look than the standard plain white background.

CSS background image

We can also use an image as our background by using the background-image CSS property and specifying an image file. It is common practice to use a small image file and repeat it many times over the web page. This helps to keep loading times down to a minimum. In order to repeat an image in either the x or y direction, or both, we can use the background-repeat property followed by either repeat-x, repeat-y or simply repeat. Take a look at the following example:

body {
	background-image: url(backdrop.gif);
	background-repeat: repeat;
	}

This code would load the file named backdrop.gif and display it as a background. The background-repeat property tells the browser to repeat the image in both the x and y direction, so that it fills the screen.

Finally there are a couple more useful background properties you should be aware of. The first one is the background-attachment property, which can take the value scroll or fixed. If you use fixed, the background image will remain stationary in relation to everything else on the web page. This means that if you scroll down the page, the image will stay anchored to the top of the actual page. If you use scroll then the background image stays anchored in the same position in relation to your browser window. If you scroll down the page now, the background image will follow you down.

The background-position property is used to set the starting point of the background image. You need to specify both an x and a y value for this property. The x value can be either left, center, right, or a % or px value. The y value can be either top, center, bottom, or a % or px value.

Bringing all of this together, our background image styling might look like this:

body {
	background-image: url(backdrop.jpg);
	background-repeat: no-repeat;
	background-attachment: fixed;
	background-position: top center;
	}

This is one of those CSS properties which can seem initially baffling, but is actually very intuitive once you get the hang of it. The best way to get it straight in your mind is to try it out for yourself and play about with the settings until you understand what they all do.