Home > Web Front-end > CSS Tutorial > What is the Difference Between :focus, :focus-visible, and :focus-within in CSS?

What is the Difference Between :focus, :focus-visible, and :focus-within in CSS?

Patricia Arquette
Release: 2025-01-28 16:06:11
Original
438 people have browsed it

Table of contents

  • The :focus pseudo-class
  • The problem with :focus
  • Interactions using the keyboard
  • The :focus-visible pseudo-class
  • What about :focus-within?
    • Practical use case for :focus-within
  • Further reading

As you may know, there are three similar sounding pseudo-classes in CSS, namely :focus, :focus-visible, and :focus-within.

At the first glance, one might get confused about the difference between these and when to use which one. The good news is: these three pseudo-classes are extremely simple to understand and distinguish from one another.

In this article, we shall understand what exactly is :focus, :focus-visible, and :focus-within, and when and how to use each one of these pseudo-classes.

Further reading:
If you need a refresher on pseudo-classes, hop over to the chapter CSS Pseudo Classes, in our CSS course.


The :focus pseudo-class

First things first, the :focus pseudo-class applies to an element when it's focused.

This focus can be made using the mouse (when we click on the element), the keyboard (when we navigate to it by pressing Tab), or the underlying program (when we use JavaScript).

Further reading:
You can explore the :focus pseudo-class in detail in CSS Pseudo Classes: :focus.

Furthermore, only focusable elements are allowed to receive focus and, therefore, be the subject of :focus. These are typically interactive elements in HTML — the likes of ,