Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The :focus pseudo-class and when it is applied

The :focus selector is used to style elements that have focus in the general sense. But when exactly is it applied, considering cases like mouse down or touch? And how as a web developer can I control it to be consistent?

e.g. here on Stack Overflow, if I mouse down on one of the links, but do not activate, by moving the mouse off before releasing, the link gets keyboard focus (as seen by then pressing tab, the focus goes to the next link). However it does not get the :focus style even though it has focus. If I tab onto a link though, I get the :focus outline style.

But on one of the websites I am working on, the mouse down gives me the :focus style straight away, so there must be some subtle detail.

In this snippet, the <a> and <button> elements in Chrome for me work like my former description, and the clickable <div> seems to work like the latter. But on one of my sites the latter is happening in all 3 cases, and I am not even sure why they are not all the same in this snippet, since I have no extra styles or JS here.

$('button').on('click', function() {});
$('.fake-btn').on('click', function() {});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  <a href="www.example.com">A link</a>
</p>
<p>
  <button>A button</button>
</p>
<p>
  <div class="fake-btn" tabindex="0">A clickable element</div>
</p>

Recording of snippet

In IE11 Everything works like the default <a> and <button> in the GIF, including on my other sites. Maybe this is a Chrome bug, or is there still some subtle bit of the spec I missed about when a :focus style gets applied? Does the order of pseudo-class CSS rules matter here in some non-obvious way?

like image 226
Fire Lancer Avatar asked Aug 31 '16 10:08

Fire Lancer


1 Answers

:focus is the psuedo selector that relates to which field is currently selected by the keyboard. Tabbing through inputs should apply :focus to that input.

:active is the pseudo selector that relates to "activating" a button or link. So clicking or touching it will apply :active to that element.

In CSS...

button:active {
    border: solid red 1px;
}

This will add a border of 1px that is red while you take action on that element making it the active link being clicked.

button:focus {
    border: solid red 1px;
}

This will do the same styling when you tab into that button. For :focus to work in some cases the tabindex is important. For the same :focus styling to work on buttons make sure to include a tabindex on them.

If you need more help, let me know.

like image 113
javascriptjames Avatar answered Nov 04 '22 19:11

javascriptjames