Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

css
communitycreator

What is the CSS focus selector?

Farounbi Abiola

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The CSS focus selector is a user action pseudo-class selector, which means it requires some interaction by the user to be used.

The CSS selector, combined with the :focus pseudo-class, is used to style an element that is targeted by the keyboard or focused on by the mouse.

Syntax

The syntax for the :focus selector is as follows:

css-selector:focus {
  // css rules
}

The CSS selector can either be a class, ID, or HTML attribute. The :focus keyword specifies the element that receives focus either through keyboard or mouse events, as shown in the example below:

.container:focus{
    border:1px solid black;
}

The container class is set to have a border when it is focused on.

Most form elements, such as <input> and <textarea>, have default focus styles, depending on the browser. In cases where users click or tab through using the keyboard, the default styles are displayed.

Code

The code below displays the default style of the <input> element when selected.

Demo Example

With the :focus selector, the style can be changed to our preference, as shown below:

Demo Example

It is important to note that accessibility must be prioritized in developing a user interface. For styling elements with the :focus selector, the Web Content Accessibility Guidelines (WCAG) must be followed carefully.

Browser compatibility

The focus selector is limited to certain browsers, such as:

  • Google Chrome 4.0
  • Microsoft Edge 12.0
  • Internet Explorer 8.0
  • Firefox 2.0
  • Safari 3.1
  • Opera 9.6

RELATED TAGS

css
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring