-2

In this exercise I was curious to learn how the first-child selector works. Trying to select the h1 tag and give it a color for example.

.col1:first-child {
  color: green;
}
<div class="col1">
  <h1> This is  something awesome!</h1>
  <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorlike).</p>
  <button type="button" class="button">Click Me!</button>
</div>

Note: The question relates only to the first-child and how it actually works, as I think that the h1 is the first child of div col1 but with no effect.

enigma
  • 3,476
  • 2
  • 17
  • 30
Duhanes
  • 389
  • 1
  • 3
  • 10
  • 1
    Possible duplicate of http://stackoverflow.com/questions/4219260/target-the-first-and-last-anchor-in-an-unordered-lists-list-item or http://stackoverflow.com/questions/2717480/css-selector-for-first-element-with-class?rq=1 or one of the other 50 times this question has been asked here :-) – TylerH Feb 10 '17 at 15:26
  • @TylerH: The two of these are completely different questions... – BoltClock Feb 10 '17 at 15:30
  • @BoltClock They both tell you how to use :first-child correctly. – TylerH Feb 10 '17 at 15:33
  • Possible duplicate of [CSS selector for first element with class](http://stackoverflow.com/questions/2717480/css-selector-for-first-element-with-class) – Jorn Feb 10 '17 at 15:36

1 Answers1

0

.col1:first-child means "A member of col1 that is the first child of its parent" not "The first child of each element that is a member of col1".

For that you need to insert a child combinator:

.col1 > :first-child {}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I had a thorough answer to this question from years ago but I had written it to [debunk the same misconception in an otherwise completely unrelated question](http://stackoverflow.com/posts/4195253/revisions). I'm still looking for a question on this subject that's worth migrating it to. And this question ain't it :( – BoltClock Feb 10 '17 at 15:45
  • Thank you for explaining that! – Duhanes Feb 10 '17 at 15:51