0

I have 5 divs.

<div class="itemA">First of Item A</div>
<div class="itemA"></div>
<div class="itemB">First of Item B</div>
<div class="itemB"></div>
<div class="itemB"></div>

I want to apply the background-color: #ccc for the first element of itemA, and for the first element of ItemB. This just the only solution works for me, because i'm aplying this css by a part of an another solution.

So, here is my CSS:

.itemA, .itemB{
  width: 200px;
  height: 30px;
  border-top: 2px solid #fff;
  background-color: #000;
}

.itemA:first-child,
.itemB:first-child{
  background-color: #ccc;
}

And here is the expectations:

Unexpected (actual working):
- Gray
- Black
- Black
- Black
- Black
Expected:
- Gray
- Black
- Gray
- Black
- Black

What Am I doing bad, what is the solution for this problem?

JSfiddle

  • 4
    `:first-child` selects the element that is the first child. That's it. Not the first child of a specific class. – j08691 Jan 25 '17 at 14:14
  • This question has been asked and answered many times. Bottom line is there is no `first-child-with-same-class` selector. –  Jan 25 '17 at 14:16
  • You're trying to use `:first-child` to mean "filter to the first element matching the selector", but actually it means "filter the elements matching the selector to exclude those that are not the first child of their parent element (in the overall page structure)". Commenting instead of answering because I don't know a way to do what you want off hand, but I'll think about it... – Mark Adelsberger Jan 25 '17 at 14:16
  • Oh, I understood the problem. Thank you all! – József Király Jan 25 '17 at 14:21
  • @JózsefKirály, you can use javascript to do what you want. create js file or in the script tag: var itemA = document.querySelectorAll(".itemA"); var itemA = document.querySelectorAll(".itemB"); itemA[0]style.backgroundColor="#ccc"; itemB[0]style.backgroundColor="#ccc"; – Some Dude Jan 25 '17 at 14:35

0 Answers0