Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting classes with nth-child

I'm looking for help with using the nth-child CSS selector. If you take a look at my HTML...

<div id="report">
    <div class="a">A</div>
    <div class="a">A</div>
    <div class="a">A</div>
    <div class="a">A</div>
    <div class="b">B</div>
    <div class="a">A</div>
    <div class="a">A</div>
    <div class="a">A</div>
    <div class="a">A</div>
    <div class="b">B</div>
    <div class="a">A</div>
    <div class="a">A</div>
    <div class="a">A</div>
</div>

...I have a row of letters like this:

AAAABAAAABAAA

I want to only show the first B and hide the others, however I cannot seem to select the classes as I expect. When I try to use:

.b:nth-child(1){
    display: block;
}

.b:nth-child(n+2){
    display: none;
}

It doesn't work and I have to select it using (5) to just get the first B.

Help would be greatly appreciated.

JSFiddle: http://jsfiddle.net/SrM9T/1/

like image 880
adamjld Avatar asked Jun 10 '14 12:06

adamjld


People also ask

Can we use Nth child for class?

The :nth-child selector allows you to select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.

What will nth child even select?

nth-child accepts two keywords in that spot: even and odd. Those should be pretty obvious. “Even” selects even numbered elements, like the 2nd, 4th, 6th, etc. “Odd” selects odd numbered elements, like 1st, 3rd, 5th, etc.

How do you target the nth child in SCSS?

Writing Complex :nth-child() Selectors It works exactly the same as :nth-child except that it starts from the end of the parent. For example, you can select the first three children of a parent by using the selector :nth-child(-n + 3) . You can use :nth-last-child(-n + 3) to select the last three.

Is nth child a pseudo element?

Pseudo-class :nth-child()The :nth-child() pseudo-class represents an element that has an+b siblings before it in the document tree, for any positive integer or zero value of n, and has a parent element.


2 Answers

This does not require javascript

.b ~ .b{
    display:none;
}   

http://jsfiddle.net/KYAj8/1/

General sibling combinator

The general sibling combinator selector is very similar to the adjacent sibling combinator selector The difference is that that the element being selected doesn't need immediately succeed the first element, but can appear anywhere after it.

More info

like image 165
Nigel Angel Avatar answered Sep 21 '22 11:09

Nigel Angel


this is your jquery

$('.b').not('.b:eq(0)').hide();

Demo

like image 32
Amit Kumar Avatar answered Sep 22 '22 11:09

Amit Kumar