2

HTML:

<body>
      <h1>First heading</h1>
      <h1>Second heading</h1>
</body>

CSS:

h1:last-child{
   color: blue;}

So the problem is that the last h1(Second Heading) is not getting styled, although it`s the last child of its parent(body). This issue occurs with "a" and other tags too, but work perfectly fine with "p".

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
  • are you testing the code locally or using online tools like codepen? – Temani Afif May 08 '20 at 13:44
  • :last-child is a pseudo-class that selects the target element if it is the last child of some other element. That is, :last-child will match the element only if it is the last child of its parent. So in your example, the h1 would have to be the last child in – Rob Moll May 08 '20 at 13:46

2 Answers2

2

Try Enclosing your H1 tag within a div

 h1:last-child{
          color:blue;
        }
     <body>
      <div>
          <h1>First heading</h1>
          <h1>Second heading</h1>
      </div>
    </body>
  
Vignesh A
  • 289
  • 7
  • 19
1

The problem is that in your HTML or IDE, the second h1 is not the last child.

Here's how it looks in jsFiddle:

enter image description here

The body element has four children, and the last child is a script element.

So to make it work, you would have to remove all other elements or, in this case, select the third from the last child. jsFiddle demo

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701