'Styling does not all apply [duplicate]

I want to override the css of <h1> and <h2> using selector (specific using selector only) but it's not working. It's getting only applied to one class only <h1> color changes to green not <h2>.

Please help can someone tell me where I am wrong. Please help!

.temp {
  color: blue;
}
.temp2 {
  color: red;
}
p .temp,.temp2{
  color: green !important;
}
<p>
  hi there this is a test page
<h1 class="temp">heading inside p tag</h1>
<h2 class="temp2">2nd heading inside p tag</h2>

</p>
css


Solution 1:[1]

Try this:

.temp {
  color: blue;
}
.temp2 {
  color: red;
}
div .temp,
div .temp2{
  color: green !important;
}
<div>
    hi there this is a test page
    <h1 class="temp">heading inside p tag</h1>
    <h2 class="temp2">2nd heading inside p tag</h2>
</div>

Solution 2:[2]

.temp {
  color: blue;
}
.temp2 {
  color: red;
}
span .temp, .temp2{
  color: green !important;
}
<span>
  hi there this is a test page
<h1 class="temp">heading inside p tag</h1>
<h2 class="temp2">2nd heading inside p tag</h2>
</span>

Answer:

  • putting h1/h2 content inside p is invalid (You might have noticed in Stack overflow's snippet editor)
  • Imagine having a huge heading inside small paragraph
  • so change to span/div/etc (in html+css)

Solution 3:[3]

You have missed to mention the paragraph element for temp2

.temp {
  color: blue;
}
.temp2 {
  color: red;
}
p .temp,p .temp2{
  color: green !important;
}
<p>
  hi there this is a test page
<h1 class="temp">heading inside p tag</h1>
<h2 class="temp2">2nd heading inside p tag</h2>

</p>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ninja_corp
Solution 2 Neptotech -vishnu
Solution 3 0stone0