CSS How to style a specific <li>?
Using jQuery, I wanted to know how I can style a specific list item?
For example, I'd like to style the first <li>
(first-child) to give it its own style, then give the next five list items heir own styles, and then the next five their own styles, etc.
I read som开发者_如何学Cething a long time ago about :nth
but didn't quite understand it. Is this easy to achieve?
nth-child
allows you to provide an expression which is evaluated to give a set of elements. The simplest expression you can provide is just a number (e.g. nth-child(3)
) which will apply the style to the 3rd child.
You can use it to apply styles to every 3rd child by using an expression such as 3n
, and can even use odd
or even
to apply styles to (obviously) every odd or even child.
However, I don't think you can use it apply styles to repeated blocks of multiple elements (e.g. style 5 elements one way, and the next 5 another) with a single expression.
Google helps a lot: http://css-tricks.com/how-nth-child-works/
ul li:nth-child(5) {
color: #ccc;
}
Or jQuery: http://api.jquery.com/nth-child-selector/
$("ul li:nth-child(5)").css("color", "#ccc");
To style groups of LI:
$(document.body).click(function () {
$("ul li").each(function (index) {
// This will get the remainder of the division of the li index by 10
var groupNum = index % 10;
// Style groups of 5 LIs differently
if (groupNum<5) {
$(this).css("color", "#ccc");
} else {
$(this).css("color", "#222");
}
});
});
Not tested, but it should give you the idea.
精彩评论