tags:

views:

178

answers:

4

I have a standard list of links:

<li><a href="">one</a></li>
<li><a href="">two</a></li>

If I want to add an extra class to one of the list items, should I add the class to the li or the a element? What is best practice?

Many thanks!

Cameron

+1  A: 

What is it that you want to style, the list item or the anchor. You probably want to style the anchor, so add it to that

Allen
+8  A: 

If you're styling the list item, such as in creating a menu, then add the class to the list item. If you want to change the appearance of the link, add it to the anchor tag.

There's really no one right answer. You should style the one that makes the most sense semantically. In many cases you may need to style both the list item and the anchor, in which case you should add the class to the li tag and define your styles for both.

li.myclass {
    /* li styles */
}

li.myclass a {
    /* link styles */
}

This is pretty much what alex suggested. The second style targets only those links wrapped in list items of your class.

Bill the Lizard
I deleted some comments that didn't make much sense after the edit I made 2 hours ago. I didn't mean to be rude, it's just that the comments no longer applied.
Bill the Lizard
No problem... :-)I just wondered why you incorporated my *constructive* criticism into your answer, when another answer already said the same thing...(Feel free to delete these comments now, they're not on topic.)
Andrew Vit
I don't mind being corrected, so these comments are okay. I just don't like it when I read an answer that says X, then see a comment that says "You should have mentioned X." It can be a little confusing.
Bill the Lizard
That's a good answer :P
alex
+5  A: 

I generally would add it to the list item.. this gives you the flexibility to target with CSS the list item or the anchor tag it contains

li.class-name {
    /* target li class */

}

li.class-name a {
    /*target it's anchor */
}

In production though, you're better off leaving the initial li off the class name when referencing it. It is unnecessary (unless you have a really bad memory).

alex
Please leave an explanation if you are going to downvote.
alex
A: 

If you want to just assign a style to one of the links in your list then use an id instead of a class. Like so.

<li id="new_style"><a href="">one</a></li>

And style it like so:

#new_style { margin: 1em; font-weight: 600; }

Victor Duwon