user1390378
user1390378

Reputation: 433

Why border is not changing on hover?

Here is my code:

<html>
<head>
<style type="text/css">
   p:hover{border:2px solid red;}
</style>
</head>
<body>
   <p style="border:2px solid green;">This is a paragraph.</p>
</body>
</html>

I am confused: why is the border color not changing on hover?

Upvotes: 0

Views: 1591

Answers (3)

Dawson
Dawson

Reputation: 7597

If you only have access to the CSS (say, because another department owns the HTML, or it's being introduced through another method), you'll have to use !important. Use of !important is absolutely fine, as it was intended to be a remedy to situations exactly like this. The idea of it being "bad practice" is wrong (unless you're using it to be lazy about your CSS specificity).

p:hover{border:2px solid red !important}

<body>
    <p style="border:2px solid green">foobar</p>
</body>

Browsers don't have a built-in CSS declaration for p:hover like they do for an a:hover, a:active, a:visited, etc; thus, the inline style in the HTML is the ONLY style being recognized at run-time. Unless... there's an !important available to give :hover a style.

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318738

Inline styles have a higher priority than any CSS rule that is not !important. So the solution is to mark the attributes in the p:hover rule as important:

p:hover {
    border:2px solid red !important;
}

Another option would be moving the initial style into the <style> tag, too.

p {
    border: 2px solid green;
}

p:hover {
    border: 2px solid red;
}

Here is a TL;DR-style explanation of CSS priorities and if you prefer something a bit longer you can also have a look at the relevant part of the CSS spec.

Upvotes: 5

drahnr
drahnr

Reputation: 6886

Inline styles have a higher priority than separate css sections

EDIT: sigh 2nd - just a tad too slow.

This should work - as far as I know !important is not considered good practice, so I'd suggest to use this approach:

<style type="text/css">
p{border:2px solid green;}
p:hover{border:2px solid red;}
</style>
<body>
<p>foobar</p>
</body>

Upvotes: 2

Related Questions