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>
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?
: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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With