The :focus-within CSS pseudo-class

Paul Ryan - Feb 11 '20 - - Dev Community

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.

. . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player