1 Thing A Week 1 Thing
A Week

Creating a CSS only menu with :has()

Week 255.0 — 13th September '22

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.

<nav>
  <input type="checkbox" id="primary-nav" />
  <label for="primary-nav">Menu</label>
  <ul>
    <li>Home</li>
    <li>About</li>
    <li>Contact</li>
  </ul>
</nav>

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;
}
More from 1 Thing A Week
« Food Wars Filling the gap between gas and electric cars: PHEVs I've just posted my first video review to YouTube on my new channel; IRL Tech Reviews Initial thoughts on the iPhone 14 Pro »

Advertisement

Notable

Quick links and commentary on interesting articles, videos and more throughout the week.

  1. 255.3 – Wednesday
    1. Hit The Island – iPhone 14 Pro game concept @ksmolka on twitter.com

Jump to notable items for Week #254, Week #256 , view the notable archive or my favourites.

About 1 Thing A Week

A website curated by @cchana bringing you 1 Thing A Week, delivered every Monday morning.

You can find a list of all articles in the archive, or read the most popular.

Find out more about 1 Thing A Week or read the privacy policy.

Market

Visit the market and support 1 Thing A Week.

You can find 1 Thing A Week on Twitter, Facebook, Instagram & Reddit