The :focus-within CSS pseudo-class

paulryan7

Paul Ryan

Posted on February 11, 2020

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.

💖 💪 🙅 🚩
paulryan7
Paul Ryan

Posted on February 11, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

king of hearts
html king of hearts

June 2, 2024

Earth Day Frontend Challenge
devchallenge Earth Day Frontend Challenge

April 24, 2024

Earth Day Frontend Challenge
devchallenge Earth Day Frontend Challenge

April 24, 2024