skip to Main Content

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.

2

Answers


  1. You can increase the specificity of your :focus-visible rule by modifying the selector to be more specific than #container > a. Since #container > a has a higher specificity, adding an ID or another selector to a:focus-visible can ensure it takes precedence:

    CSS:

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

    This ensures that when the anchor is in the :focus-visible state, the red color will override the yellow from #container > a.

    Login or Signup to reply.
  2. # 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search