3 ms·
could you use the :checked or :has selector for opening up mobile menus? i currently use JS for that and feel a bit guilty about it, yet i dont really know how
by swyx 4y ago
could you use the :checked or :has selector for opening up mobile menus? i currently use JS for that and feel a bit guilty about it, yet i dont really know how to do it in pure CSS and hide the checkbox somehow
- zachrip 4y agoBe careful in this space, keep accessibility in mind when doing things like this. JS is meant for interactivity, don't feel guilty for using it for the right job.
- chatmasta 4y agoYes, this is what I do, with :checked and <details> and some sibling selector trickery instead of :has (basically, the checkbox is the last element, and <details> is an accessible browser-native way to toggle visibility without javascript). I was able to make some complex hover menus and sidebar toggles work like this entirely without JavaScript. It's also accessible, to the user. The downside is that for the developer, the resulting code is not easy to read nor maintain. I would link to it but it's in a private repository atm. One day I'll open source this behavior as its own package... one day...
- swyx 4y agochuck it in a codepen maybe?
- cookie_monsta 4y agoYou just hide the checkbox the way you normally would with CSS. Search for CSS Hamburger Menu - there are plenty of examples online. There's some other trick in there using target. It's been a while since I did it but once you get your head around it it's pretty simple.
- aloer 4y agoan example of this is used for modals in daisyui -> https://daisyui.com/components/modal/# https://daisyui.com/components/modal/# the relevant style applied looks like this: .modal-open, .modal:target, .modal-toggle:checked+.modal { pointer-events: auto; visibility: visible; opacity: 1; }
- extra88 4y agoUnfortunately, that lacks any of the semantics or properties a modal dialog should have, like role="dialog", managing focus when the dialog opens or closes, or making the page contents behind the modal inert (if the contents behind a modal aren't inert, it's not a modal).
- arcanemachiner 4y agoYou can also trigger the behaviour of Daisy components with CSS classes (and a sprinkle of JS). But yeah, their whole "CSS + :checked elements only" model really makes my brain hurt sometimes (e.g. the [Drawer](https://daisyui.com/components/drawer/ https://daisyui.com/components/drawer/) component... nothing is where it belongs).
- extra88 4y agoYou can, but shouldn't. Visually, it can work fine but misusing the semantics of a checkbox will be confusing to screen reader users and may make it difficult to operate for a voice control user. Stick to using a button with an aria-expanded state to toggle. You can make the sibling menu contents visible based on that state. button.menu[aria-expanded="false"] + .menu-list { display: none; } button.menu[aria-expanded="true"] + .menu-list { display: block; }