Reputation: 97
<div class="one">
<div> </div>
<div class="three"> </div>
<div class="four"> </div>
</div>
<div class="one">
<div> </div>
<div class="three"> </div>
<div class="four"> </div>
</div>
<div class="one">
<div> </div>
<div> </div>
</div>
I would like to select the first div with class four, I dont want to select any other div with class four, only the very first one.
How do I accomplish that with CSS?
Upvotes: 0
Views: 99
Reputation: 7344
The most suitable way to select it is the first snippet following. But there can be many ways to select it.
.one:nth-of-type(1) > .four{
color: red;
background: pink;
}
<div class="one">
<div> First div 1st Child</div>
<div class="three">First div 2nd child</div>
<div class="four">First div 3rd Child </div>
</div>
<div class="one">
<div>2nd div first child </div>
<div class="three">2nd div 2nd child</div>
<div class="four">2nd div 3rd child </div>
</div>
<div class="one">
<div> </div>
<div> </div>
</div>
div:first-of-type > .four{
color: red;
background: pink;
}
<div class="one">
<div> First div 1st Child</div>
<div class="three">First div 2nd child</div>
<div class="four">First div 3rd Child </div>
</div>
<div class="one">
<div>2nd div first child </div>
<div class="three">2nd div 2nd child</div>
<div class="four">2nd div 3rd child </div>
</div>
<div class="one">
<div> </div>
<div> </div>
</div>
Upvotes: 3
Reputation: 14810
This can be done using the :first-child
selector as below
CSS
.one:first-child >.four {
background-color:red;
height:50px;
width:50px;
}
You can target that div using .one:first-child >.four
Upvotes: 1
Reputation: 3314
You can do this simply with first-child
. You would call your class + first-child
then the div. Telling it you only want the first instance of the class you called.
one:first-child .four
says you only want the four
class of the first one
class.
Here is an example: jsfiddle.
.one:first-child .four{
/* Your code here...*/
}
Upvotes: 4
Reputation: 510
You will have to define them uniquely. Grabbing class "one" refines the scope to all elements whose class="one".
If you want specifically that item you can identify it with an "id" instead of a class. id="four" or something unique.
ID's are generally meant for allowing for individual access, while class is generally meant for grouping elements to change all at once. You may use both attributes on the same element.
Upvotes: 2