How to remove focus around buttons on click

HtmlCssTwitter Bootstrap

Html Problem Overview


My buttons all have a highlight around them after I click them. This is in Chrome.

Unselected Selected

<button class="btn btn-primary btn-block">
    <span class="icon-plus"></span> Add Page
</button>

I am using Bootstrap with a theme, but I'm pretty sure that's not it: I was noticing this before on another project.

It goes away if I use an <a> tag instead of <button>. Why? If I wanted to use <button> how would I make it go away?

Html Solutions


Solution 1 - Html

I found this Q and A on another page, and overriding the button focus style worked for me. This problem may be specific to MacOS with Chrome.

.btn:focus {
  outline: none;
  box-shadow: none;
}

Note though that this has implications for accessibility and isn't advised until you have a good consistent focus state for your buttons and inputs. As per the comments below, there are users out there who cannot use mice.

Solution 2 - Html

You want something like:

<button class="btn btn-primary btn-block" onclick="this.blur();">...

The .blur() method correctly removes the focus highlighting and doesn't mess up Bootstraps's styles.

Solution 3 - Html

my understanding is that the focus is first applied following the onMouseDown event, so calling e.preventDefault() in onMouseDown may be a clean solution depending on your needs. This is certainly an accessibility friendly solution, but obviously it adjusts the behaviour of mouse clicks which may not be compatible with your web project.

I am currently using this solution (within a react-bootstrap project) and I do not receive a focus flicker or retained focus of buttons after a click, but I am still able to tab my focus and visually visualize the focus of the same buttons.

Solution 4 - Html

2021 focus-visible Solution

Note 1: In each of the 3 options outlined below, buttons behave the same way (no focus ring on click), but selects and inputs vary slightly in their default behavior. Only Option 3 removes focus rings consistently around buttons, inputs, and selects. Please compare all approaches and make sure you understand the implications.

Note 2: Due to the cascading nature of CSS, the order of the CSS rules is important.

Note 3: There are still some accessibility concerns with any focus-visible approach. Namely, that until browsers expose a configuration to let users choose when to show visible focus rings, focus-visible should be considered worse for accessibility than using focus rings everywhere all the time, but better than the harmful :focus {outline:none} approach mentioned in other answers to this question. See "A note about accessibility" section at the bottom of this answer for more details.

OPTION 1: Use the :focus-visible pseudo-class

The :focus-visible pseudo-class can be used to remove outlines and focus rings on buttons and various elements for users that are NOT navigating via keyboard (i.e., via touch or mouse click).

> Warning: As of 2021, the :focus-visible pseudo-class is ** widely supported across modern browsers but fails on fringe browsers**. If old-browser support is important, the Javascript polyfill in option 2 below is the closest approximation.

/**
 * Remove focus styles for non-keyboard focus.
 */
:focus:not(:focus-visible) {
  outline: 0;
  box-shadow: none;
}

/**
 * Cross-browser styles for explicit focus via 
 * keyboard-based (eg Tab) navigation or the
 * .focus-visible utility class.
 */
:focus,
.focus-visible:focus:not(:focus-visible) {
  outline: 0;
  box-shadow:
    0 0 0 .2rem #fff,
    0 0 0 .35rem #069;
}

<h3>Defaults:</h3>
<button>Foo</button>
<input type="button" value="Bar"/> 
<select><option>Baz</option></select>
<input type="text" placeholder="Qux"/>
<textarea placeholder="Quux" rows="1"></textarea>

<h3>Force focus on click:</h3>
<button class="focus-visible">Foo</button>
<input class="focus-visible" type="button" value="Bar"/> 
<select class="focus-visible"><option>Baz</option></select>
<input class="focus-visible" type="text" placeholder="Qux"/>
<textarea class="focus-visible" placeholder="Quux" rows="1">
</textarea>


OPTION 2: Use a .focus-visible polyfill

This solution uses a normal CSS class instead of the pseudo-class mentioned above and has wider browser support (in 2021). It requires either 1 or 2 Javascripts be added to your HTML; one for the official focus-visible polyfill and the other for older browsers that don't support classList.

Note: In Chrome, the polyfill seems to treat selects differently than the native :focus-visible pseudo-class.

/**
 * Cross-browser focus ring for explicit focus 
 * via keyboard-based (eg Tab) navigation or the
 * .focus-visible utility class.
 */
:focus {
  outline: 0;
  box-shadow:
    0 0 0 .2rem #fff,
    0 0 0 .35rem #069;
}

/**
 * Remove focus ring for non-explicit scenarios.
 */
:focus:not(.focus-visible) {
  outline: 0;
  box-shadow: none;
}

<h3>Defaults:</h3>
<button>Foo</button>
<input type="button" value="Bar"/> 
<select><option>Baz</option></select>
<input type="text" placeholder="Qux"/>
<textarea placeholder="Quux" rows="1"></textarea>

<h3>Force focus on click:</h3>
<button class="focus-visible">Foo</button>
<input class="focus-visible" type="button" value="Bar"/> 
<select class="focus-visible"><option>Baz</option></select>
<input class="focus-visible" type="text" placeholder="Qux"/>
<textarea class="focus-visible" placeholder="Quux" rows="1">
</textarea>

<!-- place this code just before the closing </html> tag -->
<script src="https://cdn.polyfill.io/v2/polyfill.js? 
features=Element.prototype.classList"></script>
<script src="https://unpkg.com/focus-visible"></script>


OPTION 3: Use a global key-navigation vs mouse-navigation state

An inverse solution to focus-visible, is to disable outlines on mousemove, and enable them on keydown -> "Tab". In this case, rather than specifying which elements shouldn't show an outline, you must specify which elements should.

document.addEventListener("mousemove", () => 
  document.body.classList.remove("focus-visible")
);

document.addEventListener("keydown", ({key}) => 
  (key === "Tab") && document.body.classList.add("focus-visible")
);

/**
 * Cross-browser focus ring for explicit focus 
 * via keyboard-based (eg Tab) navigation or the
 * .focus-visible utility class.
 */
:focus {
  outline: 0;
  box-shadow:
    0 0 0 .2rem #fff,
    0 0 0 .35rem #069;
}

/**
 * Remove focus ring for non-explicit scenarios.
 */
body:not(.focus-visible) :focus:not(.focus-visible) {
  outline: 0 !important;
  box-shadow: none !important;
}

<h3>Defaults:</h3>
<button>Foo</button>
<input type="button" value="Bar"/> 
<select><option>Baz</option></select>
<input type="text" placeholder="Qux"/>
<textarea placeholder="Quux" rows="1"></textarea>

<h3>Force focus on click:</h3>
<button class="focus-visible">Foo</button>
<input class="focus-visible" type="button" value="Bar"/> 
<select class="focus-visible"><option>Baz</option></select>
<input class="focus-visible" type="text" placeholder="Qux"/>
<textarea class="focus-visible" placeholder="Quux" rows="1">
</textarea>

A note about accessibility

Removing all focus rings a la :focus { outline: none; } or :focus { outline: 0; } is a known accessibility issue and is never recommended. Additionally, there are folks in the accessibility community who would rather you never remove a focus ring outline and instead make everything have a :focus style — either outline or box-shadow could be valid if styled appropriately.

Finally, some folks in the accessibility community believe developers should not implement :focus-visible on their websites until all browsers implement and expose a user preference which lets people pick whether all items should be focusable or not. I personally don't subscribe to this thinking, which is why I provided this solution that I feel is far better than the harmful :focus { outline:none }. I think :focus-visible is a happy medium between design concerns and accessibility concerns. As of 2022, Chrome browser has exposed a user preference to set focus visibility styles, but FireFox has not.

Resource:

Demo:

Solution 5 - Html

Can't believe nobody has posted this yet.

Use a label instead of a button.

<label type="button" class="btn btn-primary btn-block">
<span class="icon-plus"></span> Add Page
</label>

Fiddle

Solution 6 - Html

Although it's easy to just remove outline for all focused buttons (as in user1933897's answer), but that solution is bad from the accessibility point of view (for example, see Stop Messing with the Browser's Default Focus outline)

On the other hand, it's probably impossible to convince your browser to stop styling your clicked button as focused if it thinks that it's focused after you clicked on it (I'm looking at you, Chrome on OS X).

So, what can we do? A couple options come to my mind.

  1. Javascript (jQuery): $('.btn').mouseup(function() { this.blur() })

You're instructing your browser to remove the focus around any button immediately after the button is clicked. By using mouseup instead of click we're keeping the default behavior for keyboard-based interactions (mouseup doesn't get triggered by keyboard).

  1. CSS: .btn:hover { outline: 0 !important }

Here you turn off outline for hovered buttons only. Obviously it's not ideal, but may be enough in some situations.

Solution 7 - Html

This worked for me. I created a custom class which overrides the necessary CSS.

.custom-button:focus {
    outline: none !important;
    border: none !important;
    -webkit-box-shadow: none !important;
    box-shadow: none !important;
}

enter image description here

The -webkit-box-shadow will work for Chrome and safari browsers.

Solution 8 - Html

This works for me, another solution not mentioned. Just throw it in the click event...

$(this).trigger("blur");

Or call it from another event/method...

$(".btn_name").trigger("blur");

Solution 9 - Html

I find a solution. when we focus, bootstrap use box-shadow, so we just disable it(not enough reputation, cannot upload image :( ).

I add

.btn:focus{
    box-shadow:none !important;
}

it works.

Solution 10 - Html

If you use the rule :focus { outline: none; } to remove outlines, the link or control will be focusable but with no indication of focus for keyboard users. Methods to remove it such with JS like onfocus="blur()" are even worse and will result in keyboard users being unable to interact with the control.

The hacks you can use, that are sort of OK, includes adding :focus { outline: none; } rules when users interacts with the mouse and remove them again if keyboard interaction is detected. Lindsay Evans has made a lib for this: https://github.com/lindsayevans/outline.js

But i would prefer to setting a class on the html or body tag. And have control in the CSS file of when to use this.

For example (inline event handlers is for demonstration purposes only):

<html>
<head>
<style>
  a:focus, button:focus {
    outline: 3px solid #000;
  }
  .no-focus a, .no-focus button {
    outline: none;
  } 
</style>
</head>
<body id="thebody" 
onmousedown="document.getElementById('thebody').classList.add('no-focus');"
onkeydown="document.getElementById('thebody').classList.remove('no-focus');">
	<p>This her is <a href="#">a link</a></p> 	
	<button>Click me</button>
</body>
</html>

I did put togheter a Pen: http://codepen.io/snobojohan/pen/RWXXmp

But beware there are performance issues. This forces repaint every time the user switches between mouse and keyboard. More about Avoiding Unnecessary Paints http://www.html5rocks.com/en/tutorials/speed/unnecessary-paints/

Solution 11 - Html

I've noticed the same and even though it really annoys me, I believe there is no proper way of handling this.

I would recommend against all the other solutions given because they kill the accessibility of the button completely, so now, when you tab to the button, you won't get the expected focus.

This should be avoided!

.btn:focus {
  outline: none;
}

Solution 12 - Html

If the above doesn't work for you, try this:

> .btn:focus {outline: none;box-shadow: none;border:2px solid > transparent;}

As user1933897 pointed out, this might be specific to MacOS with Chrome.

Solution 13 - Html

Late, but who knows it may help someone. The CSS would look like:

.rhighlight{
   outline: none !important;
   box-shadow:none
}

The HTML would look like:

<button type="button" class="btn btn-primary rHighlight">Text</button> 

This way you can keep btn and it's associated behaviors.

Solution 14 - Html

For people wanting a pure css way to do that:

:focus:not(:focus-visible) { outline: none }

This could also work for link and so on, and bonus, it keeps the keyboard accessibilities. Lastly it is ignored by browsers that don’t support :focus-visible

Solution 15 - Html

I mentioned this in a comment above, but it's worth listing as a separate answer for clarity. As long as you don't need to ever actually have focus on the button, you can use the focus event to remove it before it can apply any CSS effects:

$('buttonSelector').focus(function(event) {
    event.target.blur();
});

This avoids the flicker that can be seen when using the click event. This does restrict the interface, and you won't be able to tab to the button, but that isn't a problem in all applications.

Solution 16 - Html

Style

.not-focusable:focus {
	outline: none;
    box-shadow: none;
}

Using

<button class="btn btn-primary not-focusable">My Button</button>

Solution 17 - Html

Try this solution for remove border around the button. Add this code in css.

Try

button:focus{
outline:0px;
}

If not works then use below.

button:focus{
 outline:none !important;
 }

Solution 18 - Html

It is work, I hope help you

.btn:focus, .btn:focus:active {
    outline: none;
}

Solution 19 - Html

For anyone who's using react-bootstrap and encountered this problem, here's what I did to make things work:

.btn:focus {
    /* the !important is really the key here, it overrides everything else */
    outline: none !important;
    box-shadow: none !important;
}

And things did not work before adding !important.

Solution 20 - Html

We were suffering a similar problem and noticed that Bootstrap 3 doesn't have the problem on their tabs (in Chrome). It looks like they're using outline-style which allows the browser to decide what best to do and Chrome seems to do what you want: show the outline when focused unless you just clicked the element.

Support for outline-style is hard to pin down since the browser gets to decide what that means. Best to check in a few browsers and have a fall-back rule.

Solution 21 - Html

Another possible solution is to add a class using a Javascript listener when the user clicks on the button and then remove that class on focus with another listener. This maintains accessibility (visible tabbing) while also preventing Chrome's quirky behaviour of considering a button focused when clicked.

JS:

$('button').click(function(){
    $(this).addClass('clicked');
});
$('button').focus(function(){
    $(this).removeClass('clicked');
});

CSS:

button:focus {
    outline: 1px dotted #000;
}
button.clicked {
    outline: none;
}

Full example here: https://jsfiddle.net/4bbb37fh/

Solution 22 - Html

.btn:focus:active {
  outline: none;
}

this removes the outline on click, but keeps the focus when tabbing (for a11y)

Solution 23 - Html

This works best

.btn-primary.focus, .btn-primary:focus {
-webkit-box-shadow: none!important;
box-shadow: none!important;
}

Solution 24 - Html

  .btn:focus,.btn:active, a{
    	outline: none !important;
    	box-shadow: none;
     }

this outline:none will work for both button and a tag

Solution 25 - Html

You can set tabIndex="-1". It will make browser to skip this button when you TAB through focusable controls.

Other "fixes" suggested here, only remove focus outline, but still leaves buttons tabable. However, from usability point of view, you already removed glow, so your user won't know what is currently focused button, any way.

On other hand, making button non-tabable have accessibility implications.

I'm using it to remove focus outline from X button in bootstrap modal, which have duplicate "Close" button at the bottom any way, so my solution have no impact on accessibility.

Solution 26 - Html

Add this in CSS:

*, ::after, ::before {
    box-sizing: border-box;
    outline: none !important;
    border: none !important;
    -webkit-box-shadow: none !important;
    box-shadow: none !important;
}

Solution 27 - Html

I found a solution simply add below line in your css code.

button:focus { outline: none }

Solution 28 - Html

I found no solid answers that didn't either break accessibility or subvert functionality.

Perhaps combining a few will work better overall.

<h1
  onmousedown="this.style.outline='none';"
  onclick="this.blur(); runFn(this);"
  onmouseup="this.style.outline=null;"
>Hello</h1>

function runFn(thisElem) { console.log('Hello: ', thisElem); }

Solution 29 - Html

A bit nuclear, but this is simple way that worked for me on Angular 9. Use with causon since it affects every html element.

*:focus {
  outline: 0 !important;
}

Solution 30 - Html

Although the CSS solutions offered here work,

for anyone who prefers to use the Bootstrap 4 way, as suggested in the official Bootstrap Theming guide, this should help:

in your custom.scss file (see guide above ^) where you add your variable overrides, add the following variable to remove the box-shadow for buttons:

// import bootstrap's variables & functions to override them
@import "node_modules/bootstrap/scss/functions";
@import "node_modules/bootstrap/scss/variables";
@import "node_modules/bootstrap/scss/mixins";

// override the variables you want (you can look them up in node_modules/bootstrap/scss/variables file, they're the ones that have the !default keyword at the end)
$btn-focus-box-shadow: none;

// option A: include all of Bootstrap (see the above guide for other options)
@import "node_modules/bootstrap/scss/bootstrap";

this works for me.

please note that there are many variables in bootstrap's variables file for box-shadow, for other controls as well, so it might require some more research on your side if you want to use them and/or this specific variable doesn't work for you.

Solution 31 - Html

If you want to accomplish the removal of the outline on mousedown but not on keyboard tab, and you're using VueJS, here's the solution:

<button @mousedown="$event.preventDefault()">No Online On Click</button>

This basically prevents it from receiving focus on click, but any other way of receiving focus stays active.

Solution 32 - Html

I just had this same problem on MacOS and Chrome while using a button to trigger a "transition" event. If anyone reading this is already using an event listener, you can solve it by calling .blur() after your actions.

Example:

 nextQuestionButtonEl.click(function(){
    if (isQuestionAnswered()) {
        currentQuestion++;
        changeQuestion();
    } else {
        toggleNotification("invalidForm");
    }
    this.blur();
});

Though if you're not using an event listener already, adding one just to solve this might add unnecessary overhead and a styling solution like previous answers provide is better.

Solution 33 - Html

If you're using a webkit browser (and potentially a browser compatible with webkit vendor prefixing), that outline belongs to the button's -webkit-focus-ring pseudoclass. Simply set it's outline to none:

*:-webkit-focus-ring {
  outline: none;
}

Chrome is such a webkit browser, and this effect happens on Linux too (not just a macOS thing, although some Chrome styles are macOS only)

Solution 34 - Html

I was having the same problem using <a> acting as button and I discovered I was missing a workaround by adding attr type="button" makes it behave normally for me at least.

<a type="button" class="btn btn-primary">Release Me!</a>

Solution 35 - Html

directly in html tag (in a scenario where you might want to leave the bootstrap theme in place elsewhere in your design)..

examples to try..

<button style="border: transparent;">
<button style="border: 1px solid black;">

..ect,. depending on the desired effect.

Solution 36 - Html

For sass users, Bootstrap 4 should be manipulated by overriding variables.

If you want to disable the box-shadow on focus around buttons:

$btn-focus-box-shadow: none;

You can also disable the box-shadow on focus around inputs with:

$input-focus-box-shadow: none;

Or both with one variable:

$input-btn-focus-box-shadow: none;

Solution 37 - Html

Here are two possible solutions.

1.) button type="button" className="btn-cart"onClick{(event)=>this.blur(event)}

2.) button type="button" className="btn-cart" onclick={this.blur}

Both of the solutions will remove the highlighted part around the button i.e -> blur() has its own specification in it of removing highlighted part around.

Solution 38 - Html

React with TS solution

  const btnRef = useRef<HTMLButtonElement | null>(null);
  const handleOnMouseUp = () => {
    btnRef.current?.blur();
  };
  
  <button
    ref={btnRef}
    onClick={handleOnClick}
    onMouseUp={handleOnMouseUp}
  >
    <span className="icon-plus"></span> Add Page
  </button>

Solution 39 - Html

If the button:focus {box-shadow: none} didn't work out for you there might be some library adding the border as in my case with the pseudo-selector ::after.

So I removed the border showing up on focus with the following solution:

button:focus::after {
    outline: none;
    box-shadow: none;
}

Solution 40 - Html

If you dont want the outline for button with all the status, you can override the css with below code

.btn.active.focus, .btn.active:focus, 
.btn.focus, .btn:active.focus, 
.btn:active:focus, .btn:focus{
  outline: none;
}

Solution 41 - Html

Add this in script

$(document).ready(function() {
    $('#addBtn').focus(function() {
        this.blur();
    });
});

Solution 42 - Html

For AngularJS developers I use from the solution:

var element = $window.document.getElementById("export-button");
    if (element){
        element.blur();
    }

Remember to inject $window.

Solution 43 - Html

I am curious as to why someone would want to remove the outline. Like many have mentioned, there are accessibility concerns if you remove the outline. Users using Assistive Technologies such as screen readers need to know where the focus is when visiting websites/applications. I know the blue color around the button can "mess up" designs, however, you can change the color with CSS using:

outline-color: your color hex here;

Another way you can edit this is by adding a boarder on focus.

Solution 44 - Html

Just try one of these:

outline:0; or outline:0px; or outline: none;

and $(this).trigger("blur");

Solution 45 - Html

You can use focus event of button. This worked in case of angular

<button (focus)=false >Click</button

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSean Clark HessView Question on Stackoverflow
Solution 1 - Htmljerimiah797View Answer on Stackoverflow
Solution 2 - HtmlcshottonView Answer on Stackoverflow
Solution 3 - HtmlpjsView Answer on Stackoverflow
Solution 4 - HtmlJamesWilsonView Answer on Stackoverflow
Solution 5 - HtmlAdam McKennaView Answer on Stackoverflow
Solution 6 - HtmlAlexisView Answer on Stackoverflow
Solution 7 - Htmlmenaka_View Answer on Stackoverflow
Solution 8 - HtmlRobView Answer on Stackoverflow
Solution 9 - HtmlnuclearView Answer on Stackoverflow
Solution 10 - HtmlsnobojohanView Answer on Stackoverflow
Solution 11 - HtmlOscar BolañosView Answer on Stackoverflow
Solution 12 - HtmlalnsView Answer on Stackoverflow
Solution 13 - HtmlStephanie WycheView Answer on Stackoverflow
Solution 14 - Htmlich_cbView Answer on Stackoverflow
Solution 15 - HtmlCharlesView Answer on Stackoverflow
Solution 16 - HtmlBogdan KanterukView Answer on Stackoverflow
Solution 17 - HtmlRana AalamgeerView Answer on Stackoverflow
Solution 18 - HtmlДмитрий БудницкийView Answer on Stackoverflow
Solution 19 - Htmltimthedev07View Answer on Stackoverflow
Solution 20 - HtmlTeknoFiendView Answer on Stackoverflow
Solution 21 - HtmlSeb WoolfordView Answer on Stackoverflow
Solution 22 - HtmlyenneferView Answer on Stackoverflow
Solution 23 - Htmluser8790423View Answer on Stackoverflow
Solution 24 - HtmlMilan PanigrahiView Answer on Stackoverflow
Solution 25 - HtmlzmechanicView Answer on Stackoverflow
Solution 26 - HtmlGabriel ReisView Answer on Stackoverflow
Solution 27 - HtmlManish Kumar SrivastavaView Answer on Stackoverflow
Solution 28 - HtmlKeith DCView Answer on Stackoverflow
Solution 29 - HtmlNobodySomewhereView Answer on Stackoverflow
Solution 30 - Htmlwebpassion101View Answer on Stackoverflow
Solution 31 - HtmlTetraDevView Answer on Stackoverflow
Solution 32 - HtmljospablosView Answer on Stackoverflow
Solution 33 - HtmlNate SymerView Answer on Stackoverflow
Solution 34 - HtmlspcsLrgView Answer on Stackoverflow
Solution 35 - HtmlNoneView Answer on Stackoverflow
Solution 36 - HtmlTimothePearceView Answer on Stackoverflow
Solution 37 - HtmlSurenView Answer on Stackoverflow
Solution 38 - Htmluser11533590View Answer on Stackoverflow
Solution 39 - HtmlKia KahaView Answer on Stackoverflow
Solution 40 - HtmlSabrina LuoView Answer on Stackoverflow
Solution 41 - HtmlRenish GotechaView Answer on Stackoverflow
Solution 42 - HtmlTomasz WaszczykView Answer on Stackoverflow
Solution 43 - HtmldaceyView Answer on Stackoverflow
Solution 44 - HtmlMostafaView Answer on Stackoverflow
Solution 45 - HtmlriteshView Answer on Stackoverflow