Search code examples
csspseudo-class

Pseudo class :focus doesn't propagate, now what?


Question: How do I get this to work for tabbing, using CSS only? (Tabbing already works).

#menu:before {
  content:"Menu \25bc";
  font-weight:bold;
  width:100%;
}
#menu:hover:before {
  content:"Menu \25b2";
}
#menu li {
  position:absolute;
  left:-9999px;
}
#menu:hover li {
  position:relative;
  left:0;
}
<html>
  <title>Test</title>
  <body>
    <header>
      <a href="#header1">Link to homepage</a>
    </header>
    <nav>
      <ul id="menu">
        <li><a href="#menu1">Menu item 1</a></li>
        <li><a href="#menu2">Menu item 2</a></li>
      </ul>
    </nav>
    <main>
      <p>Other text with maybe a <a href="#main1">link here</a>.</p>
    </main>
  </body>
</html>

EDIT: Original question follows.

I have a menu:

<ul id="menu">
  <li><a href="#">Menu item 1</a></li>
  <li><a href="#">Menu item 2</a></li>
</ul>

However, I want to hide it at a narrow page width, so I apply the following CSS:

@media (max-width: 768px) {
  #menu:before {
    content:"Menu \25bc";
  }
  #menu:hover:before {
    content:"Menu \25b2";
  }
  #menu a {
    position:absolute;
    left:-9999px;
  }
  #menu:hover a {
    position:relative;
    left:0px;
  }
}

This hides the menu, adds the word "Menu" in it's place, with a down or up arrow, depending on the hover state, which also shows the menu when you hover over it.

The problem is that, while :hover works just fine, I cannot get both to show by tabbing to one of the tags, using the :focus pseudo class. (Alas, :root will not work like other pseudo classes, so something like #menu a:focus:root #menu a { position:relative; left:0; } won't work, as far as I can see).

Does anyone have any ideas as to how I could approach this, using only CSS? Or have I dug myself into a hole?


Solution

  • Based on OP comment below:

    I'm happy to change the HTML, but how would :target work here?

    here is a snippet with :target

    nav {
      height: 0;
      overflow: hidden;
      position: relative;
    }
    nav:target {
      height: auto;
    }
    nav + div a:before {
      content: "Menu \25bc";
      font-weight: bold;
      width: 100%;
    }
    nav:target + div a:before {
      content: "Menu \25b2";
    }
    nav:target + div .open,
    nav + div .close {
      display: none;
    }
    nav:target + div .close,
    nav + div .open {
      display: block;
      position: absolute;
      top: 0
    }
    <nav id="menu">
      <ul>
        <li><a href="#menu1">Menu item 1</a>
        </li>
        <li><a href="#menu2">Menu item 2</a>
        </li>
      </ul>
    </nav>
    <div>
      <a class="open" href="#menu"></a>
      <a class="close" href="#"></a>
    </div>