{"id":268359,"date":"2018-03-27T06:00:46","date_gmt":"2018-03-27T13:00:46","guid":{"rendered":"http:\/\/css-tricks.com\/?p=268359"},"modified":"2020-03-30T21:08:19","modified_gmt":"2020-03-31T04:08:19","slug":"a-css-approach-to-trap-focus-inside-of-an-element","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/a-css-approach-to-trap-focus-inside-of-an-element\/","title":{"rendered":"A CSS Approach to Trap Focus Inside of an Element"},"content":{"rendered":"\n

I recently read this article<\/a> by Keith Grant which introduced the newly arrived <dialog><\/code><\/a><\/a>. Excited by this new UI element, I immediately sat down to experiment with it to see how it can be used effectively as a modal\u200a\u2014\u200athe most common use of it. While experimenting, I discovered a neat CSS trick on how to trap focus within the element, a common accessibility requirement for modals, and a notoriously difficult one.<\/p>\n\n\n\n

Disclaimer: The <dialog><\/code> demos in this article are tested on Chrome and Firefox browsers only. Safari has some weird issue where not all elements are focused while doing normal keyboard navigation with Tab key!<\/p>\n\n\n\n\n\n\n

What is focus trapping?<\/h3>\n\n\n

First, a quote from the W3C documentation<\/a> regarding what should happen following a keypress inside a dialog:<\/p>\n\n\n\n

Tab:<\/p>