skip to Main Content

How when I hover on the <li>I can select my <a>element ?

a ul:hover {
  color: red;
}
<a href="#">Link</a>
<ul>
  <li>Element 1</li>
  <li>Element 2</li>
</ul>

2

Answers


  1. For those browsers which support :has you can use:

    <style>
      a:has(+ ul li:hover) {
        background: red;
      }
    </style>
    <a href="#">Link</a>
    <ul>
      <li>Element 1</li>
      <li>Element 2</li>
    </ul>

    However, check on caniuse.com that there is enough support for your use case – Edge/Chrome/Safari support it but Firefox requires a flag to be set.

    Login or Signup to reply.
  2. You can do this using :has like this:

    a:has(+ ul:hover) {
      color: red;
    }
    <a href="#">Link</a>
    <ul>
      <li>Element 1</li>
      <li>Element 2</li>
    </ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search