Home > Software engineering >  How to apply a not selector on a a:visited selector?
How to apply a not selector on a a:visited selector?

Time:12-21

I need to apply a **visited ** style to specific links on my pages. I'm trying to use the :not selector to avoid some classes starting with btn.

Here is my CSS at this point :

a:visited :not(class^='btn'){
    color: var(--main-grey);
}

Of course, if I'm here, it's because it is not working at all :-)

Page is built on simple HTML/CSS/JS, no fancy code that could save me !

Many thanks in advance for your participation in helping me solve this issue :-) Matt

CodePudding user response:

You used the selector:

a:visited :not(class^='btn')

But this was supposed to be the correct selector for the class attribute:

a:visited:not([class^='btn'])

https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

Plus The :visited CSS pseudo-class has some privacy restriction:

https://developer.mozilla.org/en-US/docs/Web/CSS/:visited

For privacy reasons, browsers strictly limit which styles you can apply using this pseudo-class, and how they can be used:

Allowable CSS properties are color, background-color, border-color, border-bottom-color, border-left-color, border-right-color, border-top-color, column-rule-color, outline-color, text-decoration-color, and text-emphasis-color.

Allowable SVG attributes are fill and stroke.

The alpha component of the allowed styles will be ignored. The alpha component of the element's non-:visited state will be used instead. In Firefox when the alpha component is 0, the style set in :visited will be ignored entirely.

Although these styles can change the appearance of colors to the end user, the window.getComputedStyle method will lie and always return the value of the non-:visited color.

The element is never matched by :visited.

That I referenced for the sake of completion but you were already just styling the color only so it didn't hit any restriction.

Here's a demo showing that the rule will correctly style the first anchor element (not having any class beginning with btn) with red color. Of course if you need to force the :visited status, if you don't first visit the link, you might just flag its status on the developer tools.

a{
  font-size: 2rem;
}

a:visited:not([class^='btn']){
    color: red;
}
<a href="http://google.com">Google</a>
<br>
<a href="http://google.com" >2ndLink</a>

CodePudding user response:

Thanks to everybody who contributed to this solution. Here is my final code :

a:visited:not([class^='btn']):not([class^='sitemap-element']):not([class*='nav-link']){
    color: var(--main-grey);
}

A bit harsh to read maybe, but it's working great :-)

  • Related