Tips for removing focus outlines on button clicks

Whenever I click on my buttons, they all have a highlighted border around them. This issue is occurring in Google Chrome.

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

I am currently using Bootstrap along with a specific theme, but I don't think that's causing the problem: I noticed this issue even on a different project before.

The highlight disappears if I use an <a> tag instead of <button>. Why is that? How can I make it go away if I prefer to use the <button> element?

Answer №1

After coming across this Q and A on a different website, I decided to try overriding the button focus style and it actually solved my issue. It seems like this problem might be specific to using MacOS with Chrome.

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

It's important to note, however, that modifying the focus style can impact accessibility. It's recommended to only do so once you have established a clear and consistent focus state for your buttons and inputs. As mentioned in the comments, there are users who rely solely on keyboard navigation and cannot use a mouse.

Answer №2

If you're looking for a solution, consider this example:

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

This way, by using the .blur() method, you can efficiently eliminate focus highlighting without any interference with Bootstrap's styles.

Answer №3

Implementing focus-visible Effectively

Note 1: The behavior of buttons remains consistent across all 3 options described below, with no focus ring displayed on click. However, the default behavior of selects and inputs varies slightly. Option 3 is the only one that uniformly removes focus rings around buttons, inputs, and selects. It is important to compare all approaches thoroughly to understand their implications.

Note 2: The order of CSS rules is crucial due to the cascading nature of CSS.

Note 3: While using the `focus-visible` approach addresses many accessibility concerns, there are still some issues to consider. Until browsers provide a configuration option for users to decide when visible focus rings should be displayed, `focus-visible` may pose accessibility challenges. Nonetheless, it is a better alternative than the detrimental `:focus {outline:none}` method mentioned in other responses. Refer to the "A note about accessibility" section at the end of this answer for additional information.

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

The :focus-visible pseudo-class can eliminate outlines and focus rings on buttons and various elements for users not navigating via keyboard (e.g., through touch or mouse click).

Warning 2: Although widely supported by modern browsers, the :focus-visible pseudo-class does not work on certain fringe browsers as of 2021. For backward compatibility, the Javascript polyfill discussed in option 2 provides a close alternative. However, caution must be exercised as Polyfill.io ceased to be a reliable source after June 2024, as per SanSec research.

/**
 * 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 (e.g., 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: Employ a .focus-visible polyfill

This solution utilizes a regular CSS class instead of the aforementioned pseudo-class and offers broader browser support as of 2021. It necessitates adding either one or two JavaScripts to your HTML document: one for the official focus-visible polyfill and the other for older browsers lacking classList support.

Note: In Chrome, the polyfill may handle selects differently compared to the native :focus-visible pseudo-class.

/**
 * Cross-browser focus ring for explicit focus 
 * via keyboard-based (e.g., 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://cdnjs.cloudflare.com/polyfill/v2/polyfill.js?features=Element.prototype.classList"></script>
<script src="https://unpkg.com/focus-visible"></script>


OPTION 3: Implement global key-navigation vs. mouse-navigation state

An alternate approach to focus-visible involves disabling outlines on `mousemove` events and enabling them on `keydown -> "Tab"`. Unlike specifying which elements should not display an outline, this method requires identifying which elements should have one.

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 (e.g., 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>

Insights on Accessibility

Eliminating all focus rings like `:focus { outline: none; }` or `:focus { outline: 0; }` poses a known accessibility challenge and is strongly discouraged. Some accessibility advocates suggest never removing a focus ring outline but ensuring every element has a `:focus` style — be it `outline` or `box-shadow`, provided it is styled appropriately.

Moreover, some members of the accessibility community advise against implementing `:focus-visible` until all browsers offer a user preference for controlling focus visibility settings universally. I differ in opinion from this stance, hence presenting a solution that strikes a balance between design aesthetics and accessibility considerations. As of 2022, Chrome allows users to set focus visibility preferences, while Firefox lacks this feature.

Resource:

Demo:

Answer №4

From what I understand, the focus is initially applied after the onMouseDown event, so implementing e.preventDefault() in onMouseDown could be a suitable solution depending on your requirements. While this approach promotes accessibility, it also alters the behavior of mouse clicks, which may not align with your project's needs.

In my current setup (using a react-bootstrap framework), I have found that this method eliminates any focus flickering or persistent focus on buttons post-click. Additionally, I am still able to navigate through focus using tab keys and visually track the focus on these same buttons.

Answer №5

It's surprising that no one has shared this information yet.

Consider using a label in place of a button.

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

Fiddle

Answer №6

While it might be tempting to simply remove the outline for all focused buttons, this approach can be detrimental from an accessibility standpoint (as discussed in Stop Messing with the Browser's Default Focus Outline).

On the flip side, persuading your browser to stop styling a clicked button as focused can be challenging, especially with browsers like Chrome on OS X.

So, what options do we have? Here are a couple that come to mind:

1) Utilize Javascript (jQuery):

$('.btn').mouseup(function() { this.blur() })

This code instructs the browser to remove focus from any button immediately after it is clicked. Using mouseup instead of click preserves the default keyboard-based interactions (since mouseup doesn't trigger with keyboard input).

2) Try CSS:

.btn:hover { outline: 0 !important }

This CSS rule disables the outline for hovered buttons only, offering a potential solution in certain scenarios despite not being ideal.

Answer №7

This solution was effective for me. I implemented a custom class that overrides the required CSS properties.

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

https://i.sstatic.net/ATC9y.png

The -webkit-box-shadow styling will function correctly on Chrome and Safari browsers.

Answer №8

I've found a solution that seems to do the trick, which hasn't been mentioned before. Simply include it in the click event...

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

Alternatively, you can invoke it from another event or method...

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

Answer №9

After some searching, I stumbled upon a solution. If we concentrate on the task at hand, Bootstrap applies a box-shadow effect, which can be easily disabled (unfortunately, lacking sufficient reputation to upload images).

I simply inserted the following code snippet:

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

And voila, it did the trick.

Answer №10

When the rule :focus { outline: none; } is used to eliminate outlines, it can make links or controls focusable without providing any indication of focus for keyboard users. Attempting to remove it with JavaScript using something like onfocus="blur()" is even worse as it will prevent keyboard users from interacting with the control.

An alternative approach that is somewhat acceptable involves adding :focus { outline: none; } rules when users interact with a mouse and then removing them if keyboard interaction is detected. Lindsay Evans has created a library for this purpose which can be found at https://github.com/lindsayevans/outline.js

In my opinion, setting a class on the HTML or body tag would be preferable. This way, control can be maintained in the CSS file regarding when to apply this approach.

Here is an example (inline event handlers are used 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 is a <a href="#">link</a></p>   
    <button>Click me</button>
</body>
</html>

I have created a Pen for this: http://codepen.io/snobojohan/pen/RWXXmp

However, it's important to note that there may be performance issues associated with this method. It triggers repainting every time a user switches between mouse and keyboard. For more information on Avoiding Unnecessary Paints, refer to http://www.html5rocks.com/en/tutorials/speed/unnecessary-paints/

Answer №11

It's frustrating to see this issue persist, but I haven't found a foolproof way to resolve it.

I strongly advise steering clear of the other suggestions as they essentially eliminate the button's accessibility. When you try to tab to the button, the expected focus won't be there.

This is definitely something to watch out for!

.btn:focus {
  outline: none;
}

Answer №12

Although a bit delayed, this information could still be beneficial to someone in need. For the CSS styling, you can use:

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

As for the HTML code, it would look like this:

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

By following this approach, you can retain the button functionality and appearance.

Answer №13

If the previous solution doesn't suit your needs, give this a shot:

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

As suggested by user1933897, this workaround could be tailored for MacOS users using Chrome.

Answer №14

Encountering a similar issue while working with a form that included a submit button styled with Bootstrap (v4.4.1). The complication arose during the development of a single-page interface using JavaScript to dynamically update the DOM. Instead of making an HTTP POST request, the form data was sent to the server through 'fetch' as a JSON string. By utilizing e.preventDefault() in the form's submit event listener, the default behavior of the form reloading the document was bypassed (since it is a single-page application aiming at minimizing server traffic to just data transmission). Consequently, without the page refresh, the submit button appeared stuck in the pressed state until the user interacted elsewhere on the window. This exemplifies the initial code snippet causing the problem:

<input type="submit" class="btn btn-primary">

To resolve the persistently pressed button issue, I implemented the following solution:

<input type="submit" class="btn btn-primary" onmouseup="this.blur()">

Answer №15

If you're looking for a simple CSS solution:

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

This method can be applied to links as well, maintaining keyboard accessibility. Additionally, it is only recognized by browsers that support :focus-visible.

Answer №16

If you are utilizing react-bootstrap and have come across this issue, here's the solution that worked for me:

.btn:focus {
    /* using !important is crucial as it overrides all other styles */
    outline: none !important;
    box-shadow: none !important;
}

Adding !important was the key to resolving the problem.

Answer №17

As mentioned earlier in a comment, it's important to highlight this method as a distinct solution for better understanding. If the button doesn't require direct focus, you can utilize the focus event to remove it before any CSS effects are applied:

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

By using this approach, the potential flicker when utilizing the click event is avoided. It does limit the functionality of the interface since tabbing to the button won't be possible, but this limitation may not hinder all applications.

Answer №18

Design

.no-hover:focus {
    border: none;
    background: none;
}

Implementation

<a class="link link-primary no-hover">Click Here</a>

Answer №19

To eliminate the border around a button, you can try this CSS solution:

Give it a shot

button:focus{
outline:0px;
}

If that doesn't do the trick, you can try the following:

button:focus{
 outline:none !important;
 }

Answer №20

This is the solution that might be of assistance to you

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

Answer №21

While it may seem extreme, I found a straightforward solution that worked for me using Angular 9. Execute with caution as it impacts all HTML elements.

*:focus {
  outline: 0 !important;
}

Answer №22

While troubleshooting a similar issue, we observed that Bootstrap 3 does not encounter the same problem with their tabs in Chrome browser. It appears that they are utilizing outline-style, allowing the browser to determine the best course of action, which results in Chrome displaying the outline when focused after clicking the element.

However, it is important to note that support for outline-style can vary as each browser may interpret it differently. It is recommended to test across multiple browsers and include a fallback rule to ensure consistent behavior.

Answer №23

One way to solve this issue is by using a Javascript listener to add a class when the user clicks on a button, and then removing that class when the button loses focus. This approach ensures accessibility for tabbing while also addressing Chrome's peculiar behavior of focusing buttons after they are clicked.

JavaScript:

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

CSS:

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

For a complete example, visit: https://jsfiddle.net/4bbb37fh/

Answer №24

.button:focus:active {
  border: none;
}

With this code, the outline will be removed when clicked but still remain focused when tabbing for accessibility.

Answer №25

This is the most effective solution

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

Answer №26

To resolve this issue, try incorporating the following line into your CSS stylesheet:

button:focus { outline: none }

Answer №27

Solution using React and TypeScript

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

Answer №28


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

This particular CSS rule will remove the outline and box shadow for both buttons and anchor tags.

Answer №29

To prevent the browser from focusing on a specific button when tabbing through controls, you can add the attribute tabIndex="-1". This will skip over that button during navigation.

While other solutions may only remove the focus outline and still allow tabbing to the button, it's important to consider usability. If the glow indicating focus is removed, users may not know which button is currently selected.

However, making a button non-tabbable can have accessibility implications.

In my case, I used this method to eliminate the focus outline from the 'X' button in a Bootstrap modal where there was already another "Close" button at the bottom. This solution did not affect accessibility because there was an alternative way for users to close the modal.

Answer №30

Include the following CSS rules:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Button inside form not triggering jQuery click event

Within a form, I have included a button that looks like this: <form> <input type="text" /> <input type="password" /> <button type="button" class="btn-login">Log in</button> </form> I want to activate the butt ...

Automatically adjust the height of a React Native view

I am working on a component that consists of three views - one at the top, another in the middle with a specific height, and the last one at the bottom. I want the top and bottom views to adjust their heights accordingly. Although this may seem straightfor ...

Activate the content when selected

Is it possible for you to create a scenario where selecting one item makes other content active or visible, like on the Apple iPhone webpage? For example, when you choose the color of the iPhone 4, the model version becomes fully visible and interactive. ...

The height of a table cell in MVC cannot be altered

Could someone please help me with changing the height of table cells in MVC using Dreamweaver? I have already created the table with the following structure, but I am struggling to adjust the cell height. Any advice or tutorials would be greatly appreciate ...

What is the correct way to load a column of images without affecting the readability of the text alongside them? (see image below)

https://i.stack.imgur.com/rBL50.png Whenever my page loads, there is a card with a vertical list of images. Due to the loading time of the images, the text appears first and gets squished as shown in the provided screenshot. Is there a way for the text to ...

Implementing a jQuery change event to filter a specific table is resulting in filtering every table displayed on the page

I have implemented a change event to filter a table on my webpage, but I am noticing that it is affecting every table on the page instead of just the intended one. Below is the code snippet: <script> $('#inputFilter').change(function() { ...

Scrolling inside a DIV with fixed positioning

Can you help me with a question? I've been using the jScrollPane plugin and I absolutely love it. However, I'm struggling to retrieve the top position of a div on the page while scrolling inside a jscrollpaned DIV. Using $(window).scroll(); works ...

Background image remains unaffected by HTML

I'm looking to update the look of a website by changing the background color to a picture. The CSS code I am using is as follows: .bg { opacity: 5; background-repeat: no-repeat; background-size: cover; background-position: 50% 100%; ...

Issue with margin:auto in Internet Explorer 5

I have been experimenting with IE11's developer tools and discovered that when changing the browser mode, everything appears as expected in Edge, 10, 9, 8, and 7. However, in IE5, the div is forced to align to the left instead of the middle. Could so ...

Attempting to automate the process of clicking a button on a webpage using cefsharp

Hello, I am currently working with cefsharp and vb.net to develop a code that will help me navigate to the next page of a specific website. The website link is: https://www.recommendedagencies.com/search#{} My goal is to extract the list of company names ...

Tips for creating a custom Menu with content overflow in a single direction

What is the goal of this task? I have developed a custom Menu in my application with 8 options. There is a need to dynamically disable certain menu options based on specific conditions (e.g. disabling the last 4 options). When a user hovers over a disable ...

Issue with Zurb Foundation: Columns are not resizing as expected

Following the setup instructions for Zurb Foundation 4, my example is ready as per the guidelines provided here. In my basic page layout with one row and 3 columns set to a width of 4 each, I noticed that when I adjust the viewport size, the column widths ...

Ensuring Navigation Elements Remain Aligned in a Single Line

I'm in the process of developing an interactive project that will be showcased on a touch screen. One of its key features is a fixed footer navigation. Currently, I am using floats to position the main navigation elements and within each element, ther ...

The CSS property -webkit-user-select does not seem to be functioning as intended

I'm currently working on a website optimized for iPads and I'm looking to avoid the copy and paste bubble that pops up when users touch and hold on an image. I want something to trigger on touchstart and ontouchend events instead. Below is my HT ...

Continuous loop of rotating background images

I've created a design with an image in the background using the following CSS: body { width: 1000px; margin: 0 auto; background: url('/images/bg.jpg') top center no-repeat; background-attachment: scroll; } The image is 2000px in wi ...

JavaScript file slicing leads to generating an empty blob

I am currently working on a web-based chunked file uploader. The file is opened using the <input type="file" id="fileSelector" /> element, and the following simplified code snippet is used: $('#fileSelector').on('change', functio ...

Submitting files using the HTML5 File API for server-side processing

I currently have a form set up like this: <form> ... <input type="file" multiple="multiple" id="images" /> <a id="add">Add</a> ... <input type="submit" value="Submit" /> </form> Upon clicking the ad ...

Angular Dashboard Framework with a personalized editing menu option

I am currently using the Angular Dashboard Framework (sdorra) and I would like to customize the edit menu. https://i.sstatic.net/I9jDI.png By default, clicking on the menu allows me to add a widget, edit the dashboard, save, and discard changes as shown ...

"Delving into the World of CSS and Live Content

ERROR: Couldn't get my CSS right, completely unrelated to dynamic content! The answer provided is quite enlightening though! I am generating tags and adding content with the help of handlebars: Here's the Handlebars code snippet: {{#each docs} ...

Converting SQL table data into an array using JavaScript

I have some JavaScript code below that connects to a database and retrieves data from a table //Establishing database connection var sql = require("mssql"); var config = { user: '****', password: '*****', server: ' ...