Ruben
Ruben

Reputation: 114

Why isn't my :nth-child selector working?

I have a very easy example:

<div class="capa4">
    <div class="micapa4 capa41">LA 41</div>
    <div class="micapa4 capa42">LA 42</div>
    <div class="capa43">Ampliar</div>
</div>

I want to click "capa43" and hide "capa42" and expand "capa41".

.capa43:active .capa4:nth-child(1) { width:100%; }

.capa43:active .capa4:nth-child(2) { display:none; }

But this doesn't seem to work. What am I doing wrong?

Upvotes: 1

Views: 445

Answers (3)

Tomek Sułkowski
Tomek Sułkowski

Reputation: 7201

You'll have to change the order of those items a bit:

<div class="capa4">
    <div class="capa43">Ampliar</div>
    <div class="micapa4 capa41">LA 41</div>
    <div class="micapa4 capa42">LA 42</div>
</div>

then you will be able to use next siblings selector:

.capa43:active ~ .micapa4:nth-child(2) { width:100%; }
.capa43:active ~ .micapa4:nth-child(3) { display:none; }

Here's a working example: http://jsbin.com/qudona/3/edit?html,css,output

Upvotes: 0

Oka
Oka

Reputation: 26355

You've confused a couple of things here.

Firstly,

.capa43:active .capa4 {}

This selector selects all .capa4 elements that are a descendant of the .capa43 class that is in an :active state. It's not 'When .capa43 is active, find .capa4 elements and style them.' It's all about relation. What you are trying here is commonly referred to as a 'parent selector', which does not exist in CSS.

Secondly,

:nth-child works on the element itself, not the parent. It asks 'Am I the Nth child of my parent?'.

To make this work with pure CSS, you'd need to restructure your HTML, and use sibling selectors.

.capa43:active ~ .micapa4:nth-child(2) {
  color: red;
}
.capa43:active ~ .micapa4:nth-child(3) {
  display:none;
}
<div class="capa4">
  <div class="capa43">Ampliar</div>
  <div class="micapa4 capa41">LA 41</div>
  <div class="micapa4 capa42">LA 42</div>
</div>

Upvotes: 3

alewitt
alewitt

Reputation: 71

This seems to answer your question. I didn't test myself, but it should work.

Change css style of an element by clicking another

css:

    #d2:target {
        display: none;
    }

html:

    <div id="d1">
      Text
    <div id="d2">Word
      <a href="#d2">My other text</a>
    </div>

Upvotes: 0

Related Questions