惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Attack and Defense Labs
Attack and Defense Labs
N
News and Events Feed by Topic
L
LINUX DO - 热门话题
PCI Perspectives
PCI Perspectives
www.infosecurity-magazine.com
www.infosecurity-magazine.com
爱范儿
爱范儿
D
DataBreaches.Net
Simon Willison's Weblog
Simon Willison's Weblog
S
Secure Thoughts
S
SegmentFault 最新的问题
博客园 - 【当耐特】
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 叶小钗
P
Proofpoint News Feed
The Hacker News
The Hacker News
T
ThreatConnect
N
News and Events Feed by Topic
T
Threatpost
The Register - Security
The Register - Security
WordPress大学
WordPress大学
博客园 - Franky
Recorded Future
Recorded Future
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Project Zero
Project Zero
大猫的无限游戏
大猫的无限游戏
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
罗磊的独立博客
Stack Overflow Blog
Stack Overflow Blog
腾讯CDC
F
Future of Privacy Forum
F
Full Disclosure
Cyberwarzone
Cyberwarzone
J
Java Code Geeks
李成银的技术随笔
Schneier on Security
Schneier on Security
Know Your Adversary
Know Your Adversary
H
Hacker News: Front Page
人人都是产品经理
人人都是产品经理
博客园_首页
Scott Helme
Scott Helme
Google DeepMind News
Google DeepMind News
美团技术团队
Malwarebytes
Malwarebytes
Last Week in AI
Last Week in AI
T
Tailwind CSS Blog
T
The Exploit Database - CXSecurity.com
G
GRAHAM CLULEY
Recent Announcements
Recent Announcements
C
CXSECURITY Database RSS Feed - CXSecurity.com

CSS-Tricks

Revealing Text With CSS letter-spacing | CSS-Tricks Technical Writing in the AI Age | CSS-Tricks Cross-Document View Transitions: Scaling Across Hundreds of Elements | CSS-Tricks Cross-Document View Transitions: Scaling Across Hundreds of Elements | CSS-Tricks The State of CSS Centering in 2026 | CSS-Tricks Stack Overflow: When We Stop Asking | CSS-Tricks Cross-Document View Transitions: The Gotchas Nobody Mentions | CSS-Tricks What’s !important #11: 3D Voxel Scenes, Flying Focus, CSS Syntaxes, and More | CSS-Tricks Computing and Displaying Discounted Prices in CSS | CSS-Tricks rotateX() | CSS-Tricks rotateY() | CSS-Tricks rotateZ() | CSS-Tricks rotate() | CSS-Tricks Soon We Can Finally Banish JavaScript to the ShadowRealm | CSS-Tricks Using CSS corner-shape For Folded Corners | CSS-Tricks A Scrollytelling Gift for Mum on Mother’s Day 2026 | CSS-Tricks Google’s Prompt API | CSS-Tricks Making Zigzag CSS Layouts With a Grid + Transform Trick | CSS-Tricks Fixed-Height Cards: More Fragile Than They Look | CSS-Tricks What’s !important #10: HTML-in-Canvas, Hex Maps, E-ink Optimization, and More | CSS-Tricks The Importance of Native Randomness in CSS | CSS-Tricks contrast() | CSS-Tricks contrast-color() | CSS-Tricks Let’s Use the Nonexistent ::nth-letter Selector Now | CSS-Tricks Quick Hit #126 Recreating Apple’s Vision Pro Animation in CSS | CSS-Tricks Quick Hit #125 Enhancing Astro With a Markdown Component | CSS-Tricks Quick Hit #124 Markdown + Astro = ❤️ | CSS-Tricks Quick Hit #123 What’s !important #9: clip-path Jigsaws, View Transitions Toolkit, Name-only Containers, and More | CSS-Tricks A Well-Designed JavaScript Module System is Your First Architecture Decision | CSS-Tricks hypot() | CSS-Tricks The Radio State Machine | CSS-Tricks 7 View Transitions Recipes to Try | CSS-Tricks Quick Hit #122 Quick Hit #121 Selecting a Date Range in CSS | CSS-Tricks saturate() | CSS-Tricks justify-self | CSS-Tricks Quick Hit #120 Alternatives to the !important Keyword | CSS-Tricks Quick Hit #119 New CSS Multi-Column Layout Features in Chrome | CSS-Tricks Quick Hit #118 Making Complex CSS Shapes Using shape() | CSS-Tricks Quick Hit #117 Front-End Fools: Top 10 April Fools’ UI Pranks of All Time | CSS-Tricks Sniffing Out the CSS Olfactive API | CSS-Tricks What’s !important #8: Light/Dark Favicons, @mixin, object-view-box, and More | CSS-Tricks Quick Hit #116 Form Automation Tips for Happier User and Clients | CSS-Tricks Quick Hit #115 Generative UI Notes | CSS-Tricks Quick Hit #114 Quick Hit #113 Experimenting With Scroll-Driven corner-shape Animations | CSS-Tricks Quick Hit #112 JavaScript for Everyone: Destructuring | CSS-Tricks Quick Hit #111 Quick Hit #110 What’s !important #7: random(), Folded Corners, Anchored Container Queries, and More | CSS-Tricks 4 Reasons That Make Tailwind Great for Building Layouts | CSS-Tricks Quick Hit #109 Quick Hit #108 Abusing Customizable Selects | CSS-Tricks Quick Hit #107 The Value of z-index | CSS-Tricks Quick Hit #106 The Different Ways to Select <html> in CSS Quick Hit #105 Popover API or Dialog API: Which to Choose? Quick Hit #104 What’s !important #6: :heading, border-shape, Truncating Text From the Middle, and More Yet Another Way to Center an (Absolute) Element An Exploit ... in CSS?! Quick Hit #103 A Complete Guide to Bookmarklets Quick Hit #102 Loading Smarter: SVG vs. Raster Loaders in Modern Web Design Potentially Coming to a Browser :near() You Quick Hit #101 Distinguishing "Components" and "Utilities" in Tailwind Quick Hit #100 Spiral Scrollytelling in CSS With sibling-index() Interop 2026 Quick Hit #99 What’s !important #5: Lazy-loading iframes, Repeating corner-shape Backgrounds, and More Quick Hit #98 Making a Responsive Pyramidal Grid With Modern CSS Approximating contrast-color() With Other CSS Features Quick Hit #97 Trying to Make the Perfect Pie Chart in CSS Quick Hit #96 Quick Hit #95 CSS Bar Charts Using Modern Functions Quick Hit #94 No Hassle Visual Code Theming: Publishing an Extension Quick Hit #93
A CSS Approach to Trap Focus Inside of an Element
CSS-Tricks · 2018-03-27 · via CSS-Tricks

I recently read this article by Keith Grant which introduced the newly arrived <dialog>. 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 — the 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.

Disclaimer: The <dialog> 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!

What is focus trapping?

First, a quote from the W3C documentation regarding what should happen following a keypress inside a dialog:

Tab:

  • Moves focus to the next tab-able element inside the dialog.
  • If focus is on the last tab-able element inside the dialog, moves focus to the first tab-able element inside the dialog.

Shift + Tab

  • Moves focus to the previous tab-able element inside the dialog.
  • If focus is on the first tab-able element inside the dialog, moves focus to the last tab-able element inside the dialog.

To summarize, when inside a dialog, pressing Tab or Shift+Tab should cycle the focus within the dialog only—amongst the focusable elements inside the dialog.

This makes sense because when a dialog is open, a user is interacting only inside it and allowing the focus to escape outside the dialog would essentially be mixing contexts and possibly create a state where the user doesn’t know which element is in focus.

So, going back to the idea of a modal, our expectation would be that tabbing inside of the modal would only focus on elements inside of the modal. Anything outside of the context of the modal would be out of scope because the tab is only concerned with what is inside of it. This is what we mean by focus trapping.

An implementation with JavaScript

If we were to implement focus trapping inside a <dialog>, the most common approach would be to do the following when the dialog opens:

1. Grab all the focusable/tappable elements inside the dialog.
2. Listen for Tab and Shift+Tab keypresses and manually focus the next or previous element, respectively.
3. If the keypress happens on the first focusable element, then focus the last focusable element in the chain and vice versa.

This way, we create a loop on focus as the user presses Tab or Shift+Tab. See this W3C code snippet as an example of how this might be approached with JavaScript. You’ll see it’s quite a bit of JavaScript.

Enter :focus-within

Back to my experiment with the new <dialog> element. When thinking about focus trapping, a CSS pseudo-class (also very recent in browsers) immediately came to my mind : :focus-within.

If you have not heard about that before, it represents an element that has received focus or contains an element that has received focus. So, for example, you have a <div> and inside of it is an input element. If you want to style that <div> when the contained input has focus, you can do it like so:

div:focus-within {
  border: 2px solid red;
}

The CSS trick to focus trapping

Let’s exploit :focus-within and CSS transitions to implement a basic focus trap inside of a <dialog> element.

To summarise, here is how the trick works. When the focus is not within the dialog (and the dialog is open), we:

  1. trigger a CSS transition
  2. detect that transition completion in JavaScript
  3. focus the first element in the dialog

But first, let’s get set up. Here is the basic dialog and opening functionality:

<button id="button">Open dialog</button>
<dialog id="modal">
  <form action="">
    <label>
      <input type="text" /> Username
    </label>
    <label>
      <input type="password" /> Password
    </label>
    <input type="submit" value="Submit" />
  </form>
</dialog>
button.onclick = () => {
  modal.showModal();
}

There we go. Clicking on the button should open our dialog. Just this much code required to make a basic working modal using the new <dialog>

Note: As in the above example demo of dialog, you’ll notice some extra polyfill code to make <dialog> work in browsers where it isn’t supported.

If you opened the dialog in the example above and started tabbing several times, you may have already noticed the problem: the focus starts with elements in the dialog, but then leaves once the last element in the dialog has been passed.

This is the core of our trick. We somehow need to send the lost focus detected with :focus-within over to JavaScript so that we can send the focus back to the dialog. This is where CSS transitions come into play. A CSS transition is something that happens through CSS, but emits events in JavaScript too. In our case, we can trigger a transition on any property with a negligible (because it doesn’t matter in our case) visual difference and listen for the transition completion in JavaScript.

Note that we need to trigger this transition when the dialog is open but doesn’t have focus inside it.

dialog {
  background-color: rgb(255, 255, 255);
}
dialog[open]:not(:focus-within) {
  background-color: rgb(255, 255, 254);
  transition: background-color 0.01s;
}

Let’s see what that CSS is doing.

  1. We put a background-color of our choice on the dialog. This isn’t necessary, but ensures we have the same background color across browsers.
  2. The dialog[open]:not(:focus-within) selector applies when the dialog is open but doesn’t have focus on or inside it. This works because native element puts an open attribute when it’s open.
  3. Inside this rule, we change the background-color by a minimum amount. This is the least change required to trigger a CSS animation and at the same time not causing any visual difference for the user (remember this is a dummy transition). Also, we set the transition property with a very small duration because we want it to finish as soon as possible and get detected in JavaScript.

A touch of JavaScript

Now, all we need to do is detect the end of our triggered CSS transition and focus back the first element inside the modal, like so:

modal.addEventListener('transitionend', (e) => {
  modal.querySelector('input').focus();
});

We attach a transitionend listener on the modal and inside the callback, we focus the first input inside the modal. Done!

Limitations

This is a quick experiment I did to create a working proof-of-concept of focus trapping with the :focus-within pseudo-class. It has several limitations compared to dedicated JavaScript solutions to achieve this. Nevertheless, something is better than nothing!

Here are a couple of things this implementation lacks:

  1. According to W3C guidelines, the focus should cycle on the focusable element. But we are always focusing on the first input element. This is because without writing more JavaScript, we cannot know whether the focus was lost from the first or last element.
  2. We are always focusing back to the first input element. But there are many more focusable HTML elements that might be present before input or maybe there is not input element at all inside the modal. Again, full-fledged JavaScript solutions detect and maintain a list of all focusable elements and focus the right one.

Better (JavaScript) implementations of focus trapping

  1. As mentioned earlier, one working example is available inside the W3C documentation itself.
  2. Here is another implementation by Rodney Rehm that also listens for tab.
  3. Greg Kraus has a library that achieves this. His implementation maintains a list of selectors for all valid focusable elements.
  4. One more lightweight library to create accessible modals.

That is all for this experiment. If you liked this trick, you can follow me on Twitter where I share more articles and side projects of mine.