:focus 4m1j56
:focus is a pseudo-class used to select and style elements—usually links and form elements—that have been focused by the , either by “tabbing” using the keyboard or by clicking. 717y
Form elements, such as <input>
s, <buttons>
s, and <textareas>
s can receive focus either by tabbing using the keyboard or by clicking. An input field or a textarea are in focus when they are clicked and ready to be typed in.
When the tabs through links and form elements in a page, the browser usually adds a dotted outline around the element that is currently receiving the tab focus. The styles added by the browser are default to each browser and usually don’t look the same across browsers, so you may want to override the default styles and replace them with your own.
The browser uses the outline
CSS property in its default style sheet to add the :focus
styles to focused elements. In order to remove that and add your own :focus
styles, all you have to do is add outline: 0;
to the element whose :focus
style you want to change, and then add your own. For example:
a:focus { outline: 0; /* then add your own styles here */ }
Outlines are similar to borders, but they’re not quite the same. You can read more about outlines and how they differ from borders in the outline
property entry.
When you’re styling links using :focus
it is recommended that you provide the :focus
styles after :active
pseudo-classes are also used to style links, and they come after :focus
in the style sheet. The order mentioned is preferred to make sure that each pseudo-class’s styles get applied when necessary and are not overridden by the styles of another pseudo-class.
It’s very easy to remove the default :focus
styles applied by the browser, but it’s also very important to add your own :focus
styles after that for accessibility reasons.
Keyboard accessibility is very important and should be preserved, since many s prefer to navigate through a page using the keyboard. So, it is very important to always provide :focus
styles.
Examples 3e5p5z
The following snippet replaces the browser’s default :focus
outline style for links with a background and text color that make the links stand out when they are focused.
a:link { color: #0098D8; } a:visited { color: grey; } a:focus { background-color: black; color: white; } a:hover { border-bottom: 1px solid #0098D8; } a:active { background-color: #0098D8; color: white; }
The following code snippet turns the background color of focused input and text area fields into a light highlight yellow color, with a light red border.
input:focus, textarea:focus { background-color: #FFFF66; border: 1px solid #F47E58; }
Live Demo 2x4j2k
Tab through page in the following demo using your keyboard, or click on the input and textarea fields to focus them and see the :focus
styles.
Browser k5t66
The :focus
pseudo-class is ed in all major browsers: Chrome, Firefox, Safari, Opera 7+, Internet Explorer 7+, and on Android and iOS.