Mich Dart Mich Dart - 2 months ago 5
CSS Question

Only select the first element, regardless of type

I would like to apply a style ONLY to the absolute first element of a container, if it is an h1, h2, or h3... But, if in the same page there are different headings (h1, h2, h3), only the first one should inherit the styling.

For eg.

<div class="container">
<h2>I want to change this</h2>

<p>....</p>
<h3>But not this!</h3>
<h2>and not this!</h2>
</div>


I tried to use this code:

.container h1:first-of-type, .container h2:first-of-type, .container h3:first-of-type {
padding-top: 0 !important;
}


The problem is that both the first H2 and H3 are affected by this code.

I even tried this... but without success:

.container > h1:first-of-type, .container > h2:first-of-type, .container > h3:first-of-type {
padding-top: 0 !important;
}


How can I do this?

Answer

Now again try this,i think this is wht you are looking for

<!DOCTYPE html>
<html>
<head>
<style>
.container > h1:first-child{
    background-color: yellow;
}
.container > h2:first-child  {
    background-color: orange;
}
.container > h3:first-child {
    background-color: red;
}
</style>
</head>
<body>
<div class="container">
   <h2>I want to change this</h2>

   <p>....</p>
   <h3>But not this!</h3>
   <h2>and not this!</h2>
</div>

</body>
</html>

Comments