How to remove focus around buttons on click

后端 未结 30 1033
遇见更好的自我
遇见更好的自我 2020-12-02 04:24

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

\"Unselected\"

30条回答
  •  遥遥无期
    2020-12-02 05:04

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

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

    /** 
     * The default focus style is likely provided by Bootstrap or the browser
     * but here we override everything else with a visually appealing cross-
     * browser solution that works well on all focusable page elements
     * including buttons, links, inputs, textareas, and selects.
     */
    *:focus { 
      outline: 0 !important;
      box-shadow:
        0 0 0 .2rem #fff, /* use site bg color to create whitespace for faux focus ring */
        0 0 0 .35rem #069 !important; /* faux focus ring color */
    }
    
    /**
     * Undo the above focused button styles when the element received focus
     * via mouse click or touch, but not keyboard navigation.
     */
    *:focus:not(:focus-visible) {
      outline: 0 !important;
      box-shadow: none !important;
    }
    

    Warning: As of 2020, the :focus-visible pseudo-class is not widely supported across browsers. However the polyfill is very easy to use; see instructions below.


    OPTION 2: Use the .focus-visible polyfill

    This solution uses a normal CSS class instead of the pseudo-class mentioned above, and has wide browser support because it is an official Javascript-based polyfill.

    Step 1: Add the Javascript dependencies to your HTML page

    Note: the focus-visible polyfill requires an additional polyfill for several older browsers that don't support classList:

    
    
    
    

    Step 2: Add the following CSS to your stylesheet

    The following is a modified version of the CSS solution documented more thoroughly above.

    /**
     * Custom cross-browser styles for keyboard :focus overrides defaults.
     */
    *:focus { 
      outline: 0 !important;
      box-shadow:
        0 0 0 .2rem #fff,
        0 0 0 .35rem #069 !important;
    }
    
    /**
     * Remove focus styles for non-keyboard :focus.
     */
    *:focus:not(.focus-visible) {
      outline: 0 !important;
      box-shadow: none !important;
    }
    

    Step 3 (optional): use 'focus-visible' class where necessary

    If you have any items where you actually do want to show the focus ring when someone clicks or uses touch, then just add the focus-visible class to the DOM element.

    
    
    

    Resource:

    • https://css-tricks.com/keyboard-only-focus-styles/

    Demo:

    • https://wicg.github.io/focus-visible/demo/

提交回复
热议问题