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
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
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
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.
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).
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;
}