Web Overflow

Web Overflow

search
menu
Home

Home

Community

Community

Collections

Collections

Find Jobs

Find Jobs

Tags

Tags

Ask a question

Ask a question

Top Questions

How to center a div?chevron rightBest practices for data fetching in a Next.js application with Server-Side Rendering (SSR)?chevron rightAsync/Await Function Not Handling Errors Properlychevron rightAsync/Await Function Not Handling Errors Properlychevron rightHow can we eliminate the illusions in Large Language Models?chevron right

Popular Tags

javascript

5

css

4

nextjs

3

react

2

html

1

    profile picture

    Alfie

    upvote

    1

    downvote

    0

    star

    How to disable text selection highlighting

    clock icon

    asked 9 months ago Asked

    message

    1Answers

    eye

    2Views

    For anchors that act like buttons (for example, the buttons on the sidebar of this Stack Overflow page titled Questions, Tags, and Users) or tabs, is there a CSS standard way to disable the highlighting effect if the user accidentally selects the text?

    I realize that this could be done with JavaScript and a little googling yielded the Mozilla-only -moz-user-select option.

    Is there a standard-compliant way to accomplish this with CSS, and if not, what is the "best practice" approach?

    css

    1 Answers

    profile picture

    Alfie Chen

    answered 9 months ago

    upvote

    1

    downvote

    0

    As of now, there isn't a CSS standard way to disable text selection for anchor elements that are styled to look like buttons or tabs. The -moz-user-select property you mentioned is specific to Mozilla browsers and won't work in all browsers.

    A common approach to prevent text selection on interactive elements like buttons is to use the user-select CSS property with a value of none. This property isn't part of any standard yet, but it is supported in most modern browsers.

    Here is an example of how you can prevent text selection on anchors styled as buttons:

    a.button-like {
      user-select: none;
    }



    You can add this class to your anchor elements where you want to prevent text selection. Just keep in mind that this approach may not work in all browsers and should be used with caution.

    If you want a more robust solution that works across different browsers, you may need to use JavaScript to prevent text selection. You can listen for the selectstart and mousedown events on the elements and prevent the default behavior to stop text selection. Here is an example using jQuery:

    $(document).on('selectstart', '.button-like', function(e) {
      e.preventDefault();
    });
    
    $(document).on('mousedown', '.button-like', function(e) {
      e.preventDefault();
    });



    This way, you ensure that users cannot accidentally select the text when interacting with the button-like anchor elements.