skip to Main Content

When I hover over the <a>, it correctly changes color. But when I hover over the <p>, nothing happens. I do not understand why <p> does not change color when hovered.

If I replace the selector with p:hover, then the <p> responds correctly when hovered (but of course the <a> stops). How can I get both the <p> and the <a> to change color when hovered with just a single rule? And why doesn’t this “just work” as expected?

<html>
    <head>
        <style>
            :hover {
                background-color: black;
                color: white;
            }
        </style>
    </head>
    <body>
        <p>some text</p>
        <a href="https://stackoverflow.com">stackoverflow</a>
    </body>
</html>

To future would-be editors: This code will not demonstrate the issue in a Stack Snippet because it is caused by quirks mode in browsers, something not reproducible in Stack Snippets

2

Answers


  1. Your code is applying quirks mode because it doesn’t have a doctype. The quirks mode spec says:

    4.1. The :active and :hover quirk

    In quirks mode, a compound selector selector that matches the following conditions must not match elements that would not also match the :any-link selector. [SELECTORS4]

    • selector uses the :active or :hover pseudo-classes.

    • selector does not use a type selector.

    • selector does not use an attribute selector.

    • selector does not use an ID selector.

    • selector does not use a class selector.

    • selector does not use a pseudo-class selector other than :active and :hover.

    • selector does not use a pseudo-element selector.

    • selector is not part of an argument to a functional pseudo-class or pseudo-element.

    The :hover selector meets those conditions, so it does not match the p element.

    Login or Signup to reply.
  2. I tried your code and saw that the styles are used for all tags and the body changes color.
    If you want the tag a and p to change color to a suitable color, you must specify that only these two tags change color at the same time.

    p:hover,a:hover{
    color: red;
    background-color: blue;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search