skip to Main Content

Let’s say I’ve got a link and that has some styling.

<a href="...">Link</a>
a {
    color: #f00;
}

a:hover,
a:focus {
    color: #c00;
}

Let’s now say that I place a link in another component and want to change the link’s colour.

<div class="thing">
    <a href="...">Another link</a>
</div>
.thing a {
    color: #0f0;
}

(Let’s further say that there’s some specificity wars going on so the hover style is still used – I can appreciate that in this example, the hover styles would be overridden by the component.)

My question is: is there a way that I can prevent the link colour changing on hover?

I’ve tried these sort of settings, nothing seems to be working.

/* These don't work */
.thing a:hover,
.thing a:focus {
    color: unset;
    color: revert;
    color: currentColor;
}

My use-case is that we’re using a CSS library that’s brought in through node_modules, so I can’t directly affect the component (I can’t do something like setting the colour to a CSS custom property and just setting the hover colour to reference that). I can add to it, but I don’t know what colour the link would actually be, but it changes on hover. I’d prefer it not to and I’m looking for something that says "use the color value as if there was no state."

2

Answers


  1. Well, your question is a bit confusing. First let me rephrase for you:

    You want first link to work as usual, i.e., it’ll have color #f00 when loaded. On hover or focus, it should change it’s color to #c00.

    Then, you have this Another Link, where you want it have color #0f0 when loaded and you don’t want it to change color on focus or hover.

    Feel free to correct me if I understood it wrong 🙂

    For this scenario, I have created a test.component.html, that looks like:

    <a href="">First Link</a><br>
    <a href="">Second Link</a><br>
    <div class="thing">
        <a href="">Another Link</a>
    </div>

    Then, I created corresponding test.component.css, that looks like:

    a {
        text-decoration: none;
        color: #f00;
    
        &:focus,
        &:hover {
            color: #c00;
        }
    }
    
    .thing {
        a {
            text-decoration: none;
            color: #0f0;
    
            &:focus,
            &:hover {
                color: #0f0;
            }
        }
    }

    Now see the result:

    • Page on load

    Page on load

    • Page on hovering First Link

    Page on hovering First Link

    • Page on hovering Another Link

    Page on hovering Another Link

    Login or Signup to reply.
  2. Quick fix, just add this (>) in between thing and a tag as shown below

    <style>
    a {color: #f00;}
    a:hover,a:focus {color: #c00;}
    .thing>a {color: #0f0;}
    </style>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search