CSS - diff background img for each menu item

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

CSS - diff background img for each menu item

Post by Luke »

I often run into the problem of needing a different background image for each of my menu items (say I want to have an icon of home on the home page link, an envelope on the contact us page, etc.). I usually write a different css class for each of the menu links like this:

Code: Select all

#left_menu ul li a.home{
	background: #ccc url(images/home.jpg) no-repeat;
	color: #000;

}
#left_menu ul li a.home:hover{
	background: #ccc url(images/home.jpg) no-repeat;
        background-color: #fff;
}
#left_menu ul li a.contact{
	background: #ccc url(images/contact.jpg) no-repeat;
	color: #000;

}
#left_menu ul li a.contact:hover{
	background: #ccc url(images/contact.jpg) no-repeat;
        background-color: #fff;
}
#left_menu ul li a.page1{
	background: #ccc url(images/page1.jpg) no-repeat;
	color: #000;

}
#left_menu ul li a.page1:hover{
	background: #ccc url(images/page1.jpg) no-repeat;
        background-color: #fff;
}
Is there an easier/shorter way to do this?
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

That looks pretty standard to me ;)
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

Ya, pretty standard, but you could shorten it a bit. You don't need to declare background-color if you've already put a colour in the 'background' declaration. For example:

Code: Select all

#left_menu ul li a.home:hover{
        background: #ccc url(images/home.jpg) no-repeat;
        background-color: #fff;
}

//can be shortened to
#left_menu ul li a.home:hover{
        background: #fff url(images/home.jpg) no-repeat;
}
You also don't need to redeclare the background color and image for the 'hover' state:

Code: Select all

#left_menu ul li a.home{
        background: #fff url(images/home.jpg) no-repeat;
}

#left_menu ul li a.home:hover{
        color:#000;
}
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply