csscss-selectorspseudo-class

How to change a pseudo selectors' precedence


CSS:

#container > a {
    color: yellow!important;
}
a:focus-visible {
    color: red!important;
}

HTML:

<div id="container">
    <a href="#">Anchor 1</a>
    <a href="#">Anchor 2</a>
</div>

We all know, the text color will be still yellow when we focus on an anchor, due to the first selector is more specific. It's so weird and I think it's a bug, because :focus-visible (and other pseudo selectors like :hover) is a different state like a click event. To me it's like invoking onchange handler when I click an element. Anyways, it's completely different topic to discuss.

My question is, how can I make the "a:focus-visible" selector high precedence? #container > a:focus-visible might be the correct answer. However, think about I have lots of case in my page and my users can still add the selectors like the first. I need to push my own rule on all anchors.


Solution

  • # selector is pretty strong. You can add <body id="something"> and prefix all your rules with #something <your selector> should work. Tested:

    #container>a {
      color: yellow !important;
    }
    
    #something a:hover {
      color: red !important;
    }
    <body id="something">
      <div id="container">
        <a href="#">Anchor 1</a>
        <a href="#">Anchor 2</a>
      </div>
    </body>