DEV Community

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

Posted on

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.

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.