Dynamically Assigning Background Images to HTML Elements in CSS
by Chris Lane
While building out the website for the Go Primal Fitness gym a while ago, I encountered a somewhat interesting problem. The design called for a different background image on the html element for each “section” of the site, where sections where determined based off of anchors present in the top-level navigation.
Now assigning differing background images to the various body elements of a website is easily (and frequently) done. The implementation usually looks something like this:
body#home{
background-image: url('/the/home/image.jpg');
}
body#about-us{
background-image: url('/the/about-us/image.jpg');
}
This is a very widely-used, straightforward technique. (Implied, of course, is that in your markup, you’re simply assigning a unique ID to every body element in your site.)
Assigning differing background images to html elements is a bit trickier, though, simply because the W3C standard does not allow html elements to have IDs or classes. Read the rest of this entry »