Here's a little tip that I started using more frequently recently that involves images. When embedding images into pages you're often inclined to use an IMG tag or an ASP.NET image control. In some situations though - especially if the same image repeats on the page - it can be much more efficient to use a style that references the image rather than embedding the image into the page itself.
For example, if you look at the WebLog here and you look at the time image for each of the posts (in the byline) that image is linked in the style sheet as:
background: transparent url(images/time.gif) no-repeat;
and then embedded into the page as part of a repeater template column like this:
<%# WebUtils.WebLogDateString( ((DateTime)Eval("Entered")),true ) %>
- from <%# Eval("Location") %>
The idea is that you can use the style to display the image as a non-repeating background image and then set enough of an offset so that any content the follows will show past the image.
Now why would this be better than an embedded:
<img src='<%# this.ResolveUrl("~/images/time.gif") %>' />
First if at all possible it's a good idea to keep any formatting information that might be reused in a style sheet. I've been slow to adopt CSS in the past mainly because I've had tons of pre CSS HTML around, but once you start with CSS it's hard to stop <s>. Anyway it's a good idea to abstract whenever possible.
Second if you have repeating images you are reducing page size by not embedding image link information for every image embedded. If you embed an image 30 times or so (once for each item) given that URLs that are fully Web site pathed (ie. created with ResolveUrl - you are using ResolveUrl right? <s>) aren't exactly short. So it definitely can save some bytes returned to the client.
Finally the nice thing about images referenced by CSS files is that they are relative to the CSS file and not the page so when you reference the style there's no need to try and figure out or reference a Web site relative path (ResolveUrl) for consistency. Less code needs to run (let the browser figure it out) and the size of the page gets reduced by not repeatedly embedding the same image Url into the page.
This is nothing new of course - CSS designers have long been telling us to rely on CSS for all it's worth, but as a developer I find myself a little behind the times with some CSS concepts. This has been one of the more useful ones...
Other Posts you might also like