Adding a background image using CSS

Why would I want to use CSS to add a background image?

Adding a background image using CSS saves you time and reduces the amount of code that you need to write. Usually when you place an image as a background in html it will repeat the image across and down the page. CSS allows you to control how your image repeats in the background, if you want it to repeat horizontally and/or vertically. This method also allows you to easily change the image at a later time by just making a change to one file instead of each indiviual page.


OK, so how do I do it?

First thing you will need to do will be to create an external style sheet. Open a new page in a text editor and save it as:

style.css


Next add the following text to this file:

body { background-image: url(images/water-bkgd.jpg);}


The first part "body" tells you which tag this will apply to. The next part "background-image:" tells you what style will be applied. The third section "url(images/water-bkgd.jpg)" is the name of the background file and it's location. You can also add additional styles into this style sheet to use througout your website.


Now we will need to connect this style sheet to a webpage. Open a new page in the text editor. Add the "html", "head", and "body" tags. In the "head" section add the following text:

< link rel="stylesheet" href="style.css" type="text/css" >


This will link the style sheet to your webpage.


What if I want to change the background image?

To change your background image just change the name of the old image "(images/water-bkgd.jpg)" to that of the new image "(images/new-bkgd.jpg)".

url(images/water-bkgd.jpg)

url(images/new-bkgd.jpg)


What did I do to create this background image?

For my background I wanted the image to repeat across the page but not down. To do this I modified my background inmage in photoshop so that the left and right edges could kind of blend together. I put this code into my style sheet:

background-repeat: repeat-x;


With the first part done the image repeated itself across the page if the browser window was expanded. However, I still had white space showing under the image when the window was stretched down. To solve this problem I added a black background with this code:

background-color: black;


The complete code for the background is shown below:

body { background-image: url(images/water-bkgd.jpg);

background-repeat: repeat-x;

background-color: black;}



This handy dandy tutorial was created by Matt Malo for Graphic Interface Design, a graphic design class at Utah State University.