Hacker News new | ask | show | jobs
by toastal 1238 days ago
I don't know how I feel about using a CSS hack for this. This isn't a semantic element and a lot of other browsers like TUI browsers aren't sure what to do with this sort of element.

In my experience in many cases, just showing all of the menu items when JS is disabled is an easier, safer solution with cleaner markup and no hacks. After JS is detected, toggle a class on the document to hide the menu, build your button, insert it into the DOM. Some menus are too big, but most are not and the kinds of sites that need big menus often require interactivity with JavaScript anyways.

1 comments

That is a terrible user experience for SSR though and will lead to a layout shift every time the page is loaded.

I wouldn’t really call this a CSS “hack” either. There is a checkbox that defines whether the menu is open, and CSS that styles the menu accordingly. I think that this is rather elegant really.

As soon as the :has pseudo class has widespread support, the checkbox can also just live inside the nav element, which removes the awkward general sibling combinator.

Correct me if I'm wrong but it doesn't lead to layout shift if you attach that "has-js" or remove the "no-js" class from the document if the script is in the <head> without async/defer or so it's executed before the body and CSS are even rendered. Doing this is useful for styling other <noscript> other related situations as well.

Using a checkbox is a hack in that you are using a <input> but not as a part of a form. The vestigial element gets rendered in all sorts of contexts where the CSS isn't downloaded or used. And even still, to get the ARIA you need for this menu to be accessible, you'll need to invoke JavaScript for to set the element attribute states anyhow. The anchor is a hack as well because it's not being used to link to any ID on in the document.

I also just gave this author's site a go. If I checked the box by using the keyboard, I can't close it with the mouse (or vise versa). It's a little funny as well since the menu items fit on the site without needing to make a menu button and at a small enough breakpoints it doesn't even break the items into multiple lines. Perhaps this is the anchor that's getting hit in the other case. ...And if the author had concerns about JavaScript, they would have done the syntax highlighting on the server side as well.

I wish there was an existing element for developers to just use though since it's a common pattern at this point. Then we wouldn't need to use said hacks or involve JavaScript that many users disable by default for security/privacy.