htmlcsshoverpseudo-class

`:hover` pseudoclass not applying to `<p>`, while `p:hover` does


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


Solution

  • 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.