Style sibling selector with a:visited

443 Views Asked by At

I am showing an image element when the user hovers over a link-- this is working.

I would now like to make that image always visible to the user when they return to the site... My attempt below was (I think) foiled because of restrictions on the :visited selector.

Is there a way to get around these restrictions to make this method work? Is there another selector I can use to the same effect?

a {
  text-decoration: underline;
  color: black;
}

#image {
  position: absolute;
  visibility: hidden;
  top: 30%;
  left: 60%;
}

a:visited {
  color: red;
}

a:visited + #image {
  visibility: visible;
}

a:hover{
  color: white;
  transition: color .3s ease;
}

a:hover + #image{
  visibility: visible;
}

2

There are 2 best solutions below

0
On

There are limits to what the :visited selector can style: https://developer.mozilla.org/en-US/docs/Web/CSS/Privacy_and_the_:visited_selector

It might seem that you've run up against one.

4
On

This way we can do.

a {
  text-decoration: underline;
  color: black;
}

#image {
  position: absolute;
  visibility: hidden;
  top: 30%;
  left: 60%;
}

a:visited {
  color: red;
}

a:visited + #image {
  visibility: visible;
}

a:hover {
  color: white;
  transition: color .3s ease;
}

a:hover + #image {
  visibility: visible;
}
<a href="#hello">Hello</a> - Click this to make it visited.
<img src="http://lorempixel.com/250/250/" alt="Image" id="image" />

Also you can do this way, by using :target attribute.

a {
  text-decoration: underline;
  color: black;
}

#image {
  position: absolute;
  visibility: hidden;
  top: 30%;
  left: 60%;
}

a:visited {
  color: red;
}

#image:target {
  visibility: visible;
}

a:hover {
  color: white;
  transition: color .3s ease;
}

a:hover + #image {
  visibility: visible;
}
<a href="#hello">Hello</a> - Click this to make it visited.
<img src="http://lorempixel.com/250/250/" alt="Image" id="image" />

Check this out from MDN...

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>:target pseudoclass example</title>
    <style>
      #hidden-element {
        display: none;
      }

      #hidden-element:target {
        display: block;
      }
    </style>

  </head>
  <body>
    <p><a href="#hidden-element">Show the Hidden Element</a></p>
    <div id="hidden-element">
      <p>You have unhided me!</p>
    </div>
  </body>
</html>