Hitesh Kumar
Hitesh Kumar

Reputation: 3698

CSS: anchor link hover is not working

What I want is when I hover over anchor element the hover class should be applied. But it seems like it's not working. h1 element is inside the anchor element. So I have to select h1 element using a h1:hover then only this class is being applied. The only concern is when I apply color to h1 then hover stops working otherwise it works well. I don't know why this is happening. Can anyone please help on this? Thanks. Code pen to play

HTML:

<a href="">
  <h1>This will not work on hover</h1>
</a>

CSS:

a, a:link{
  color: teal;
}
a:hover{
  color: salmon;
}

h1{
  color: magenta;
}
/* a h1:hover{
  color: salmon;
} */

a, a:link{
  color: teal;
}
a:hover{
  color: salmon;
}

h1{
  color: magenta;
}
/* a h1:hover{
  color: salmon;
} */
<a href="">
  <h1>This will not work on hover</h1>
</a>

Upvotes: 0

Views: 2346

Answers (5)

George Antonakos
George Antonakos

Reputation: 748

CSS specificity doesn't work exactly as you think.

You can read more about this here: https://www.smashingmagazine.com/2007/07/css-specificity-things-you-should-know/

About your problem you could change:

a:hover{
    color: salmon;
}

to

a:hover h1{
    color: salmon;
}

and it will work as the above selector is more specific from:

h1{
   color: magenta;
}

and as a result it will override it when a is hovered.

Final html/css for you to test what I said:

<a href="">
   Anchor Text
   <h1>Heading Text</h1>
</a>

and

a, a:link{
  color: teal;
}
a:hover{
  color: salmon;
}

a:hover h1{
  color: yellow;
}

h1{
  color: magenta;
}

Upvotes: 2

Saurav Rastogi
Saurav Rastogi

Reputation: 9731

Try:

a, a:link{
  color: teal;
}
a:hover h1 {
  color: salmon;
}

h1{
  color: magenta;
}
/* a h1:hover{
  color: salmon;
} */
<a href="">
  <h1>This will not work on hover</h1>
</a>

Hope this helps!

Upvotes: 0

Jishnu V S
Jishnu V S

Reputation: 8409

you have missing # also , i have added one css

a:hover h1{
 color: salmon;
}

a, a:link{
  color: teal;
}
a:hover{
  color: salmon;
}

a:hover h1{
  color: salmon;
}

h1{
  color: magenta;
}
/* a h1:hover{
  color: salmon;
} */
<a href="#">
  <h1>This will not work on hover</h1>
</a>

Upvotes: 0

Prasath V
Prasath V

Reputation: 1356

Try this

a, a:link{
  color: teal;
}
a:hover h1 {
  color: salmon;
}

h1{
  color: magenta;
}
<a href="#">
  <h1>This will not work on hover</h1>
</a>

Upvotes: 0

Falguni Panchal
Falguni Panchal

Reputation: 8981

try this

demo

css

a, a h1:link{
  color: teal;
}
a h1:hover{
  color: salmon;
}

h1{
  color: magenta;
}
/* a h1:hover{
  color: salmon;
} */

Upvotes: 0

Related Questions