Another way to reduce the number of images used in your CSS

Posted on 05 July 2007 (02:39 AM)

I did some fairly obvious pondering today. In a website I'm currently working on two images are used for some pagination links. Simple images representing a white arrow on a colored background.

There's one image for the regular link state, and one image for the link's hover state, which is the same except for the differently colored background.

It just hit me I could do this with only one image.

These are two images that work in the same way:

The image for a regular link The image for a hovered link

The CSS for the link would be something like this:

  1. a {
  2. width: 100px;
  3. height: 100px;
  4. display: block;
  5. }
  6. a { background: url(pic1-normal.jpg) no-repeat; }
  7. a:hover { background: url(pic1-hover.jpg) no-repeat; }
  8. Download this code: /code/another_way_to_reduce_the_number_of_images_used_in_your_CSS1.txt

But, I can achieve the exact same effect using only one image, let's say a PNG, with a transparent background, and use CSS like this:

  1. a {
  2. width: 100px;
  3. height: 100px;
  4. display: block;
  5. }
  6. a { background: #000 url(pic1.png) no-repeat; }
  7. a:hover { background-color: #f00; }
  8. Download this code: /code/another_way_to_reduce_the_number_of_images_used_in_your_CSS2.txt

Like I said; this is all very obvious and nothing new, but sometimes it's good to read a reminder. Check out this page to see a comparison.

Related reading:

Back to top

Filed under HTML and CSS

Comments:

  1. 10 August 2007 (01:27 AM) by JD Graffam

    I believe this is what A List Apart does with their banners in the bottom right. PNGs are wonderful things. Hey, that rhymed.

Sorry, due to spam, comments are temporarily out of order.

Back to top

Preferences

These settings will be saved for your convenience.