0

I have a html like below:

<div class="A"> --- Div 0 There can be multiple of this
    <div class="B C"></div>
</div>

<div class="A"> --- Div 1
    <div class="B C D"></div>
</div>
<div class="A"> --- Div 2
    <div></div>
    <div class="B C D"></div>
</div>
<div class="A"> --- Div 3
    <div class="B C D"></div>
</div>

I want certain styling to be applied to <div class="B C D"></div> only for Div 1.

I have used css .B.C.D:first-of-type for doing this, but it is also affecting Div 3.

I donot have control over HTML and want to resolve it only using CSS

Devang Singh
  • 1
  • 1
  • 2
  • if you really need just the first div to have certain css rules applied just add a secondary class to that div only. – 404answernotfound May 16 '17 at 06:44
  • Even if you don't have control over the HTML, surely you can make *some* assumptions about it? If you can't make any assumptions at all, then this is a duplicate of [Matching the first/nth element of a certain type in the entire document](http://stackoverflow.com/questions/27524415/matching-the-first-nth-element-of-a-certain-type-in-the-entire-document) – BoltClock May 16 '17 at 06:58

1 Answers1

2

Use :first-child to get first child among a group of elements. Try this:

.A:first-child > div.B.C{
  background-color:red;
}
<div class="A"> --- Div 0 There can be multiple of this
    <div class="B C">There can be multiple of this</div>
</div>

<div class="A"> --- Div 1
    <div class="B C D"></div>
</div>
<div class="A"> --- Div 2
    <div></div>
    <div class="B C D"></div>
</div>
<div class="A"> --- Div 3
    <div class="B C D"></div>
</div>
Kiran
  • 20,167
  • 11
  • 67
  • 99