@shinyaz

HTML <details> open attribute can't be controlled with CSS media queries

1 min read

I was implementing a table of contents with <details> and wanted it open on desktop, closed on mobile. My first instinct was CSS @media — but open is an HTML attribute, not a CSS property. There's no way to toggle it with media queries.

The React solution is straightforward: check window.innerWidth on mount.

TypeScript
const [isOpen, setIsOpen] = useState(true);
 
useEffect(() => {
  setIsOpen(window.innerWidth >= 768);
}, []);
 
return (
  <details
    open={isOpen}
    onToggle={(e) => setIsOpen(e.currentTarget.open)}
  >
    <summary>Table of Contents</summary>
    {/* ... */}
  </details>
);

The onToggle handler is key — it tracks manual open/close by the user. During SSR it renders as true (open), then on the client it closes if mobile.

Share this post

Shinya Tahara

Shinya Tahara

Solutions Architect @ AWS

I'm a Solutions Architect at AWS, providing technical guidance primarily to financial industry customers. I share learnings about cloud architecture and AI/ML on this site.The views and opinions expressed on this site are my own and do not represent the official positions of my employer.