Creating a CSS only menu with :has()

Week 255 was posted by Charanjit Chana on 2022-09-13.

I want to start sharing more snippets of code, and where better to start than a CSS only menu that's driven by the :has() selector?

Worth noting, you need Safari or Chrome 105 to appreciate the beauty of it although support is getting better and better for it.

Using just CSS we can now create menus that opens and closes without JavaScript. It requires an additional HTML element (or two) and I've even managed to give it a modal background which you can click on to close again rather than relying on a single icon or word.

The HTML is simple. This is how I would implement it (and you could even get away with the sibling selector) and it allows you to have the element anywhere on the page, you just need to amend the path of the selectors to fit it together.

  <input type="checkbox" id="primary-nav" />
  <label for="primary-nav">Menu</label>

The CSS is minimal too for the raw functionality, the example above is embellished a bit to make it more demo friendly. This is genuinely all you need:

nav > #primary-nav {
    display: none;
nav > ul {
    display: none;
nav:has(#primary-nav:checked) ul {
    display: block;

Tags: css, has-css

Tweet WhatsApp Keep Upvote Digg Tumblr Pin Blogger LinkedIn Skype LiveJournal Like