CSS HowTo – Using Image Backgrounds In Your Designs

Filed under: CSS,Web Design

In this HowTo we will cover some of the methods of using CSS and images for your container backgrounds.

Almost any container can be styled with CSS this means you can apply images to your page backgrounds, Table and individual Table Cell Backgrounds, Divs and even your forms.

Most of the common declarations will apply to all elements.

Ok so lets start off easy and apply a leaf background to our page.
(the examples are representations and may not look exactly the same in all browsers.)

Applying The Image

ok so we have a leaf.png file we want to add to our body element by using css.

body {background-image: url(’/leaf.png’)}

and the result would look something like this

Limit Repeat to One Time

In our leaf example you can see that the image will repeat for the length and width of the page. We want just one image to show on the page so we can use no-repeat.

background-image:url(/leaf.png);

background-repeat:no-repeat”

Controlling the repeat direction

Often you will use special fade images that need to be applied only in one direction
Ok lets say we want to limit the repeat pattern in the x or y direction.

In this case we would control the repeat property.

background-repeat: repeat-x
background-repeat: repeat-y



Positioning the Background Image

Now something a little more tricky lets say we want to use our leaf but we need it placed in a specific place on the container or page.

We can set the no-repeat , fixed and its position in pixels.
background-repeat: no-repeat;
background-attachment:fixed;
background-position: 50px 75px;

And it should look something like this:


Setting The Transparency of the Background Image

Now this is a tricky thing to do but it can be applied on containers.

If you notice the image on the right is lighter because the white background is showing through. This will work with any image but browser compatibility can be an issue. Use this technique sparingly.

opacity: 0.4;
filter:alpha(opacity=40)


Final Note

CSS is a great tool and it should be used along with other methods to create your final design.

When possible you should always revert and rely on the simplest ways to create your projects.

When you visit many large high volume sites you may notice that they do make use of larger images to show content instead of relying on formatting that could change across browsers or because of different settings within the same browser.

You should never use css to fix things on the fly or add special tricks…. you should use it to contribute to your design because it is the best way to do something.