Focus on :focus
Understanding some of the finer quirks of how :focus works is important to build keyboard accessible stuff. Here are some quick notes on what focus is, how it works and how to force it on elements programatically.
1: What is focus.
I like the sitepoint definition of focus:
This pseudo-class matches any element that has keyboard input focus. Keyboard input focus describes any element that’s ready to receive user input. It can apply to a form control, for instance, or to a link if the user navigates using the keyboard.
This definition is pretty complete, the one thing i would add is that :focus these days can come from more than a keyboard user. Phone trackpoints, Assistive Tech and some game controllers also make use of the focus mechanism.
2: Focus only moves down the tree.
The :focus pseudo selector can only be used on elements which can receive focus and their children.
Lets say you have:
<ul> <li> <a href="http://google.com"> <span>Visit Google</span> </a> </li> </ul>
If keyboard focus is on the anchor only the :focus rules on the children of the anchor are applied. In the case above thats the nested span.
The :hover pseudo selector works the opposite way, applying the :hover rules to the parents of the element which is being hovered. In the case above, if you hovered on the anchor it would also trigger the :hover styles applied to the li.
3: Forcing focus
In some situations you may wish to force focus on a specific element programatically. For example, we use JS to push focus to the drop-down elements on the iPlayer Radio navigation when your using the keyboard.
Forcing focusing on a normally focusable elements is straight forward. Simply use the .focus() method of the DOM node.
For elements which do not receive focus natively you need to first make the element focusable. You do this by setting the tab-index property to -1.
For more discussion of how and when to force focus take a look at the discussion on stack overflow
I think that should be enough to demystify focus a little. If you have any corrections, contradictions or extra information please feel free to let me know in the comments.