DEV Community

Cover image for The :focus-within CSS pseudo-class
Paul Ryan
Paul Ryan

Posted on

1 1

The :focus-within CSS pseudo-class

Recently, while writing an article for CSS Tricks on using skip links I found myself needing to transition a div into view when an element inside the div has focus (when a keyboard user tabs onto it).

Take this Codepen that has a div which is hidden that contains an a element. We want to transition this div into view when the a gets focus.

Initially, I was going to write JavaScript to do this, but then I found out about the focus-within pseudo-class.

So, to transition our div into view all we need to do is write the following:

.hidden:focus-within {
  transform: translateY(0%);
}

That will now give us the following when tabbing our a into focus.
Tab Example

And voila! We have now achieved our goal.

I hope you learned something and it helps you out!

Complete pen.

EDIT

Sebastián Veggiani was kind enough to point out that this isn't fully supported across all browsers.

A polyfill can be found here.


Make sure to follow me on Instagram where I share tips, tricks and current stuff I am working on.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (2)

Collapse
 
sveggiani profile image
Sebastián Veggiani

Be cautious about the browser support for this: caniuse.com/#feat=css-focus-within

If you need to support browsers like IE11 or Edge Legacy you can use this polyfill:

github.com/matteobad/focus-within-...

Collapse
 
paulryan7 profile image
Paul Ryan • Edited

Ah, thanks very much Sebastián. I add it to the article.

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay