开发者

CSS :first-child to work with classes

Say i have this markup:

<div class='current'>
</div>
<div class='current'>
</div>
<div class='current'>
</div>
<div class='current'>
</div>
<div class='current'&开发者_高级运维gt;
</div>

Now these divs are not necessarily next to each other in the markup, but could be spread throughout the page.

Can i target only the first occurrence of class "current" using CSS only, i'd ideally like to avoid using javascript (for now)?

Ie.

.current:first-child {
background: red;
}


I believe you're looking for something like this:

.current:nth-child(1){
    background:red;
}

Should do the trick!


:first-child targets elements that are first children, not first occurrence of a given class. So this will target all elements with current class, that are first children. It can be all of them if they are in different places on a page or none at all.

It sounds like you may be looking for css3 selector first-of-type


As mentioned in these two answers (along with this new one), CSS3 doesn't bake in a pseudo-class that selects the first element of its class (unlike :first-of-type which selects by type).

You can always use :first-child if .current is guaranteed to be the first child of .group:

.group .current:first-child {
    background: red;
}

But if it's not guaranteed to be, then based on your comments and the answer link, since they all share the same parent you can do this instead:

.group .current {
    background: red;
}

.group .current ~ .current {
    background: transparent; /* Or whatever your default is */
}

The general sibling combinator ~ ignores other elements that may not be .current. All these rules work in IE7+.


If they are spread throughout the page, you can not get what you need with pure CSS solution. Even with first-of-type unless the elements are on the same DOM level. Check the example to see that you can not select the elements.

On the other hand once I move the third .current to the same DOM level where I already have the second one, I get only the second item selected, as it's the first .current on this level.

On the other hand it's a very short one-liner in JS

Don't overcomplicate things ;)


If it's spread throughout the page, you can't target it with css.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜