Home > other >  Select the second element of the second section with same name, CSS - NTH
Select the second element of the second section with same name, CSS - NTH

Time:09-25

In this example http://jsfiddle.net/rodrigolinkweb/k8qg14xL/ I need to select only "Container 12", how can I do this?

ps: note that both divs have the same class name "wrapper".

.container:nth-child(n 3){
   background-color: gray;
    color:white;
}
<div class="wrapper">
    <div class="container">Container 1</div>
    <div class="container">Container 2</div>
    <div class="container">Container 3</div>
</div>
<br />
<div class="wrapper">
    <div class="container">Container 11</div>
    <div class="container">Container 12</div>
    <div class="container">Container 13</div>
</div>

CodePudding user response:

You can select them with the .wrapper class, like this

.wrapper:nth-of-type(2) .container:nth-child(2){
   background-color: gray;
    color:white;
}
<div class="wrapper">
    <div class="container">Container 1</div>
    <div class="container">Container 2</div>
    <div class="container">Container 3</div>
</div>
<br />
<div class="wrapper">
    <div class="container">Container 11</div>
    <div class="container">Container 12</div>
    <div class="container">Container 13</div>
</div>

If you want to select it from backwards you can use :nth-last-of-type() . Refer to the following fiddle here

No matter what content the .wrapper has :nth-child will select child based on its position where as :nth-of-type selects with appropriate attribute.

.wrapper:nth-of-type(2) .container:nth-child(2){
   background-color: gray;
    color:white;
}
<div class="wrapper">
    <div class="container">Container 1</div>
    <div class="container">Container 2</div>
    <div class="container">Container 3</div>
</div>
<br />
<div class="wrapper">
<a href="#">Some link</a>
    <div class="container">Container 12</div>
    <div class="container">Container 13</div>
</div>

  • Related