1

I need to select a specific HTML element, which are identical, also contain inside several identical div's, I tried with nth-child() but it did not work. (Each child shares same properties with minor changes)

HTML

<div class="disc">
  <div class="disc_PF">
  </div>
</div>
<div class="disc">
  <div class="disc_PF">
  </div>
  <div class="disc_PF">
  </div>
</div>

CSS

.disc .disc_PF:nth-child(1) {}

When I use this, it selects both first disc_PF elements,

CSS

.disc .disc_PF:nth-child(2) {}

When I use this, it select third disc_PF element,

How can I select individual nested element separately?

Thanks

Matthew Beckman
  • 1,702
  • 2
  • 16
  • 28
Manoj
  • 265
  • 3
  • 13

4 Answers4

3

Here's how you could do it.

.disc_PF
{
  width: 50px;
  height: 50px;
}

/* First .disc, all .disc_PF */
.disc:nth-of-type(1) > .disc_PF
{
  background: red;
}
/* Second .disc, first .disc_PF */
.disc:nth-of-type(2) > .disc_PF:first-child
{
  background: green;
}
/* Second .disc, .disc_PF that is the second child element */
.disc:nth-of-type(2) > .disc_PF:nth-child(2)
{
  background: yellow;
}
/* Second .disc, last .disc_PF */
.disc:nth-of-type(2) > .disc_PF:last-child
{
  background: blue;
}
<div class="disc">
  <div class="disc_PF">
  </div>
</div>
<div class="disc">
  <div class="disc_PF">
  </div>
  <div class="disc_PF">
  </div>
  <div class="disc_PF">
  </div>
</div>
3

Nth child starts counting from the element's parent, so if you have two elements from different parents where each is the second child of its own parent, you will be selecting both of them.

Try this:

.disc:nth-child(2) .disc_PF:nth-child(1) {}
Marcelo Lazaroni
  • 9,819
  • 3
  • 35
  • 41
2

.disc_PF
{
 width:100px;
 height:100px;
 float: left;
}

/* 1st .disc, all .disc_PF */
.disc:nth-of-type(1) > .disc_PF
{
  border:1px solid #ccc;
  background:#ccc;
}
/* 2nd .disc, 1st .disc_PF */
.disc:nth-of-type(2) > .disc_PF:first-child
{
  border:3px double #111;
}
/* 2nd .disc, 2nd .disc_PF  */
.disc:nth-of-type(2) > .disc_PF:nth-child(2)
{
  border:1px solid #0f0;
}
/* 2nd .disc, 3rd .disc_PF */
.disc:nth-of-type(2) > .disc_PF:last-child
{
  border:1px solid #00f;
}
<div class="disc">
  <div class="disc_PF">
  1st disc_PF
  </div>
</div>
<div class="disc">
  <div class="disc_PF">
  2nd disc_PF
  </div>
  <div class="disc_PF">
  3rd disc_PF
  </div>
  <div class="disc_PF">
  4th disc_PF
  </div>
</div>
Pravin Durugkar
  • 357
  • 3
  • 21
1

:nth-of-type() and :nth-child only work on element names, not classnames. In other words,

.classname:nth-child(2) 

doesn't work, but

div:nth-child(2)

does. Similarly, something like .my-class:first-child() will not select the first element with .my-class unless it's a first child.

Given your code example, the only options you have are either to add ids to the elements, or select any <div> based on it's position (first child, etc).

JakeParis
  • 11,056
  • 3
  • 42
  • 65