simonewebdesign

A pure CSS onclick context menu

Context menus are one of those very useful UI widgets that still haven't reached the HTML spec. There have been attempts, but for now everyone tends to make their own custom implementation.

Especially with the advent of React, the tendency is to write a custom menu component that uses JavaScript to open/close itself, perhaps by using an invisible overlay to detect clicks outside the menu and close it accordingly. This works fine in practice, however it doesn't have to be so complicated. If you need a simple dropdown menu that:

  • Has no dependencies;
  • Can be triggered with a click/tap on any element;
  • Is fully cross-browser;
  • Doesn't need JavaScript!

Then look no further. It's much simpler than you think!

An example

Try clicking this button:

This is done in pure HTML and CSS; the JavaScript is there just to add functionality. Source code below.

The HTML

<button></button>
<nav class="menu">
  <ul>
    <li>
      <button onclick="alert('Hello there!')">
        Display Greeting
      </button>
    </li>
    <li>
      <button onclick="print()">
        Print This Page
      </button>
    </li>
  </ul>
</nav>

The CSS

.menu {
    visibility: hidden;
}

button + .menu:active,
button:focus + .menu {
    visibility: visible;
}

That's the trick: we hide the menu in CSS initially, then show it when the button gets focused and while we're clicking on the menu itself. This is necessary so that the click actually gets registered. That's it! No JS trickery involved.

You can attach event listeners to the menu items, e.g. using onclick or document.addEventListener and they'll work as usual. You may also just use <a> tags instead of buttons, depending on your use case.

Naturally the menu can be opened only by elements that can receive focus, such as buttons and anchors. So what about other non-interactive elements? Can we make them focusable too? The answer is yes!

A more complicated example

We want to display a context menu when clicking on the following image:

doge meme
wow, this image is clickable!

The HTML

<figure tabindex="-1">
  <img src="/images/doge.png" />

  <nav class="menu">
    <ul>
      <li>
        <button>Open Image in New Tab</button>
      </li>
      <li>
        <button>Save Image As...</button>
      </li>
      <li>
        <button>Copy Image Address</button>
      </li>
    </ul>
  </nav>
</figure>

The trick here was to add tabindex. This makes the element focusable, so that it can open the menu on click. Note that if the clickable element is a <button> or other interactive content (i.e. any focusable element), then you don't even need this!

I've used a <figure>, but you can use any element you like. Just add tabindex="-1" to make it focusable, if it isn't already. You can place the menu anywhere you want in the HTML, as long as you're able to target it with a CSS selector. Just try not to put a button in a button as that's invalid HTML, although technically it will still work.

The CSS

.menu {
    visibility: hidden;
}

figure:active .menu,
figure:focus .menu {
    visibility: visible;
}

How do I make the menu appear next to the mouse cursor?

You'll need JavaScript, but it's entirely up to you whether you want to do this. Alternatively you could add position: absolute to the menu and just make it appear below (or next to) the element you clicked — no need for JS in this case! Anyway, this did the trick for me:

const img = document.querySelector('.doge');
const menu = document.querySelector('.menu');

img.addEventListener('mousedown', ({ offsetX, offsetY }) => {
    menu.style.top = offsetY + 'px';
    menu.style.left = offsetX + 'px';
});

I want the menu to close when I click the button again!

If that's the case, you'll probably be better off using the old checkbox hack.

A note about accessibility

Accessibility isn't the main focus of this article, but an important topic nonetheless. Menu items should be navigatable with a keyboard: this requires JS, but it's not hard to achieve. The W3C has done a lot of work around accessibility and there's plenty of examples you can refer to on their site: for instance, I think the menu button example is particularly relevant.

What about browser support?

It may not work in some very old browsers, so make sure to test it in the browsers you need to support. This MDN page has some info about what happens to the focus of a button when being clicked/tapped on different platforms. I did some tests myself and it seems to work well everywhere, including IE and mobile browsers.

Update: this blog post received a lot of attention and a few folks reached out to me about an issue, specifically with Safari and Firefox, on both iOS and macOS: the button won't focus. No worries though, it only affects buttons; other tags will work just fine. You may consider using <span tabindex=0> — the semantic meaning is lost entirely here, so if you really want to use a button, you can always focus it programmatically via JS, but only on Apple devices — for example:

if (
  /apple/i.test(navigator.vendor) ||
  /Mac.*Firefox/.test(navigator.userAgent)
) {
  const button = document.querySelector('button');

  button.addEventListener('click', event => {
    event.target.focus();
  });
}

Another issue you may find specific to Apple is that the menu won't close when tapping outside of it. There's an easy fix: simply add tabindex="-1" to the container or the body tag.


And that's it! I hope you found this useful. If you spot any issues, please do let me know!

Last update:

View this page on GitHub