0

I know if I set an inline style for example for the color, it cancels style about color in the style tag or a CSS file (to reason the priority order). But why does it cancel setting a color for :hover for the same element? While it is for the hover case and not for a normal color.

a {
  background-color: #333;
  color: white;
  text-decoration: none;
  padding: 5px;
}

a:hover {
  color: yellow;
}
<a href="/" style="color: tomato">Home</a>

And how to fix that? Only with this answer? (Setting :hover in anchor tag?)

Inline style to act as :hover in CSS

Thanks for guids:)

Arman Ebrahimi
  • 2,035
  • 2
  • 7
  • 20
  • I think the problem is that you set `color` to `tomato` in the `style` attribute *and* set it to `white` in the CSS. If you remove the `style` attribute, does it work as intended? – Julia May 24 '22 at 06:43
  • 1
    pseudo-classes have the same specificity as class selectors. You could increase the specificity on `:hover` selector, or use `!important`. – cSharp May 24 '22 at 06:44
  • @cSharp Thanks, it is an appropriate answer for me. – Arman Ebrahimi May 24 '22 at 07:30
  • @Julia Yes, you're right. But I want to fix it while there is an inline styling. It only was a challenge:) thanks. – Arman Ebrahimi May 24 '22 at 07:35

2 Answers2

1

But why does it cancel setting a color for :hover for the same element?

See specificity in the specification.

A style attribute is more specific that any combination of selectors.

And how to fix that?

Avoid style attributes. Use a class and write a ruleset that targets it instead.

a {
  background-color: #333;
  color: white;
  text-decoration: none;
  padding: 5px;
}

a.foo {
  color: tomato
}

a:hover {
  color: yellow;
}
<a href="/" class="foo">Home</a>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

You are right the but if need to make the color change while hovering the text you must do like this(just Added The Important Tag):

a {
  background-color: #333;
  color: white;
  text-decoration: none;
  padding: 5px;
}

a:hover {
  color: yellow !important;
}
<a href="/" style="color: tomato">Home</a>
Arman Ebrahimi
  • 2,035
  • 2
  • 7
  • 20
Lucifer
  • 81
  • 5
  • `!important` is generally [more trouble than it is worth](https://stackoverflow.com/a/9245360/19068). It can solve a problem *once* but then, if your CSS gets more complex and you get another instance of the same problem, you can't double `!important`. – Quentin May 24 '22 at 06:47
  • but if you look that inline styles is not a good way to apply Css that make a sense if your applying style inline you are using important tag ot overruled the inline css – Lucifer May 24 '22 at 07:02
  • @Quentin Yes, you're right. Although I was looking for a solution to use `:hover` while there is an inline styling. – Arman Ebrahimi May 24 '22 at 07:23