What is the reason for the .foo a:link, .foo a:visited {} selector taking precedence over the a:hover, a:active {} selector in CSS?

Sample code: http://jsfiddle.net/RuQNP/

<!DOCTYPE html>
<html>
<head>
    <title>Foo</title>
    <style type="text/css">
        a:link, a:visited {
            color: blue;
        }

        a:hover, a:active {
            color: red; 
        }

        .foo a:link, .foo a:visited {
            color: green;
        }

        /* A possible fix */
        /*
        .foo a:hover, .foo a:active {
            color: red;
        }
        */
    </style>
</head>
<body>
    <div class="foo">
        <a href="http://example.com/">Example</a>
    </div>
</body>
</html>

Anticipated Outcome:

The link would change to red upon hovering.

Actual Result:

The link changes to green when hovered over.

Inquiries:

  1. Why does the color specified in the selector .foo a:link, .foo a:visited override the one in a:hover, a:active? What seems to be happening?
  2. I grasp that I could resolve this by uncommenting the commented code. However, I'm curious about how we can adjust the .foo a:link, .foo a:visited selector so it doesn't take precedence over the color defined in a:hover, a:active?

If my comprehension of http://www.w3.org/TR/CSS21/cascade.html#specificity is correct (Thanks, BoltClock), here's the specificity table for the different selectors in the code.

a:link         - 0 0 1 1
a:visited      - 0 0 1 1
a:hover        - 0 0 1 1
a:active       - 0 0 1 1
.foo a:link    - 0 0 2 1
.foo a:visited - 0 0 2 1

Therefore, the style set for .foo a:link takes precedence over the style for a:hover when both link and hover pseudo-classes are applied to an A element with the class foo.

Similarly, the style designated for .foo a:visited overrides the style for a:hover when both visited and hover pseudo-classes are applicable to an A element with the class foo.

Answer №1

When you delved into the world of CSS for the first time, you may have come across the mnemonic LoVe-HAte as a guide for the order in which to specify link selectors (a:link, a:visited, a:hover, a:active). Have you ever pondered why this specific mnemonic was chosen?

There's actually a interesting point made in the specification document about how link and dynamic pseudo-classes are handled when multiple rules with all of them are applied to the same element, which sheds light on the necessity of setting link selectors in that particular sequence:

It's crucial that A:hover comes after A:link and A:visited rules, as failing to do so would result in the 'color' property of the A:hover rule being obscured by cascading rules. Likewise, since A:active follows A:hover, the active color (lime) takes precedence when the user both activates and hovers over the A element.

The main takeaway here is that despite all four pseudo-classes having equal specificity, the last rule prevails among equally specific selectors. The triggering of each pseudo-class is irrelevant in determining the application of styles.

With the introduction of the simple .foo selector, your second set of link/visited rules supersedes the initial set of link/visited styles and the hover/active styles. Consequently, links within elements carrying that class will consistently appear green until additional hover/active styles are specified using the .foo selector.


I apologize if my response seems a bit rushed or disjointed; I'm currently typing this on my iPhone and it's quite challenging to gather my thoughts under these circumstances...

Answer №2

My interpretation is that all these pseudo classes have equal specificity, so the one written last takes precedence. Now, let's explore the functionality of pseudo-classes

:link, :visited, :focus, :hover, :active
individually.

a: link{color: red} instructs the user agent to make the anchor element red in any state. Execute the following script:

  a:link {
  color: red;
  
  }
<a href="www.stackoverflow.com">Go to stackoverflow </a>

The anchor element turns red in the following states only if the link is unvisited,

  • Unvisited
  • Hovered
  • Focused(Tabbed)
  • Active(Clicked)

Therefore, a: link{color: red} directs the user agent to apply a red color to the anchor element in the aforementioned states. Now, let's compare it with the a:hover pseudo-class. Run the following script

a:hover {
  color: red;
  
}
<a href="www.stackoverflow.com">Go to stackoverflow </a>

The anchor element turns red when hovered and clicked.

  • Hovered
  • Active(clicked)

We observe that both :link and :hover pseudo classes can affect the hover state -- Therefore, if you assign these two pseudo-classes to the same element, the one mentioned later in the CSS file will take precedence. This principle applies to other pseudo-classes as well. Let's outline the actions of each pseudo class.


a:link {...} defines behaviors for an unvisited link in various states:
- Focused(Tabbed)
- Hovered
- Active(Clicked)

The link state supersedes all other states.


a:visited {...} sets the behavior for visited links in the following states:
- Focused(Tabbed)
- Hovered
- Active(Clicked)

a:visited {...} prevails over all states except :link only when the link has been visited.

Please note that a link may be considered visited or unvisited based on the user agent's cache. For example, a website visited ten days ago might not be stored in the user agent's cache, thus technically remaining categorized as unvisited.


a:focus {...} dictates the behavior for visited and unvisited links in various states:
- Focused(Tabbed)
- Hovered
- Active(Clicked)

a:focus {...} takes priority over :hover and :active states.


a:hover {...} determines the behavior for visited and unvisited links when hovered:
- Hovered
- Active(Clicked)

a:hover {...} supersedes the :active state


a:active {...} specifies the behavior for visited and unvisited links when active:

  • Active(Clicked)

Answer №3

To rectify the issue, ensure that the .foo ... selector is placed first and include !important to the color value for the other link/visited selector. Here's an example:

    a:link, a:visited {
        color: blue;
    }

    a:hover, a:active {
        color: red !important; 
    }
    .foo a:link, .foo a:visited {
        color: green;
    }

The reason why the .foo a:link, .foo a:visited selector takes precedence over the other selector regardless of its position is because .foo a:link has higher specificity than a:link. The same applies for :visited. Therefore, the .foo ... selector will always override the a:link,a:visited selector due to its parent class name, making it more specific.
(For further clarification, refer to @BoltClock's explanation on LoVe - HAte - as it plays a role in this issue.)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Detect if the user is using Internet Explorer and redirect them to a different

My web application is having trouble rendering in Internet Explorer. In the meantime, I would like to detect if the user is using IE and redirect them to a different page specifically for IE visitors. What is the best way to accomplish this? Should I use ...

Having trouble with displaying the CSS background image?

I've been attempting to configure background images using CSS, but for some reason, I'm not able to get the images to show up correctly. Below is the CSS code that I'm working with: a.fb { background-image: url('img/Facebook.png&a ...

"Enhance your website design with a navbar that seamlessly blends with the background color

Question 1: I have a requirement for my navbar to affix overlay on top of the background color and image of the div (top-banner). Currently, when I scroll down, the background color overlays my navbar affix instead. How can I ensure that my navbar sta ...

(no longer supported) We are unsure about the usage of /deep/, >>>, and ::ng-deep, ::v-deep

Since /deep/ has been deprecated, I have found that using global styles instead is the only viable solution. Does anyone know of an alternative solution where we can still maintain encapsulation or scoped styling? ...

The Art of Determining the Text's Baseline

My goal is to create a test that determines whether the text rendered inside an <input> has the same baseline as a label: To achieve this, I want to calculate the baseline of the rendered text in each element and compare their values. Is it possible ...

Explore the styling options for SVG using CSS to manipulate different properties of the

After saving my SVG image in Illustrator, the code appears like this: <?xml version="1.0" encoding="utf-8"?> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBo ...

Tips on altering the quantity of columns in a ul list dynamically

I'm trying to create a list with 2 columns, and I want it to switch to 3 columns when the browser window is wide enough (for example, on a 23 inch monitor). Can this be achieved using CSS or any other method? Here is my current CSS: .search-results ...

The width specified for the table is not being applied

I've been struggling to adjust the width of my table in order to display data from a database. I've tried using inline width, !important tag, id, and class but none have worked. Interestingly, when I apply a fixed width without dynamic data, it w ...

The tab content refuses to show up in its designated fixed location

I've been working on creating a responsive tab system that functions as an accordion on smaller mobile devices, inspired by this example. I've made great progress and I'm almost where I want to be, but for some reason, the active tab content ...

Guidelines for attaching a div to the bottom of a page?

I have a navigation menu inside div.wrapper, and I am trying to make the div.wrapper stick to the footer. <div class="wrapper"> <div id="menu"> <ul> <li>1.</li> <li>2.</li> ...

Updating style of element in EJS following POST request in Node.js using Express

I am working on a form page that is supposed to display a Success Alert (Boostrap) once the user fills out the form and clicks the Submit button. <form class="well form-horizontal" action="/contact" method="post" id="contact_form"> ... (input fiel ...

Can you explain the concept of "cascading" within CSS?

Can someone kindly explain the specific definition of "Cascading" in Cascading Style Sheets (CSS)? I have heard conflicting perspectives on this topic, so I am seeking clarification here. Any examples to illustrate would be greatly appreciated. ...

When floated to the right, the element is being pushed onto the next line in Firefox

Within a div, there are four elements. I specifically want the last element to be positioned on the far right, so I applied float: right to it. However, in Firefox, the last element gets pushed to the end of the next line instead. This issue does not occ ...

What method can I use to adjust the font style when it overlays an image?

Sorry if this is a bit unclear, but I'm trying to figure out how to change only a section of my font when it overlaps with an image while scrolling. If you visit this example website, you'll see what I'm referring to: For a visual represen ...

iPhone-compatible iFrame with adaptable webpage dimensions

While attempting to embed our page on a client's site, everything looks great in a browser and our media queries are functioning properly. However, we encountered an issue when viewing the embedded page inside an iframe on an iDevice. It seems that th ...

Display issue with ul and li elements in Safari browser causing menu to appear incorrectly

Although I am new to CSS, I managed to create a menu on my website that hovers over the background video successfully. It is a basic menu using a ul with li elements and it appears as intended in all browsers except Safari. In Safari, the menu items stack ...

Is it possible to use v-if in conjunction with a style tag to specify a different source file? Alternatively, is there a more efficient method I

I attempted the example provided below, but unfortunately, it did not function as expected. The reason behind my endeavor is that adding numerous modifiers (--tuned) to achieve the desired outcome seemed impractical. Therefore, I decided to try and link ...

Developing SAPUI5: Construct a GenericTile featuring a centrally positioned icon

I'm having trouble creating a custom tile in SAP that inherits from sap.suite.ui.commons.GenericTile and only displays an icon centered in the middle of the tile. The standard aggregations and properties are causing issues as they position the icon on ...

A fixed header list using CSS with a single scroll bar

I am looking to create a scrollable list with a fixed header, where the scroll bar extends the full height of the parent but only scrolls through the nav items (keeping the logo in place). My current setup involves: <div className="home-page-nav"> ...

Adding a Click class can cause significant disruption to the entire CSS layout

I am facing an issue with transforming the X position and appending an additional class to create a slide effect in React. It seems to be working differently compared to using vanilla JavaScript. Below is the code snippet: .inputModal { position: absolut ...