skip to Main Content

similar question: CSS allow text selection within an element only
but that’s not what I want

I get two sibling elements, if the user starts a text selection inside A, then I don’t want any other text outside A to be select-able

in the snippet, I tried using a contenteditable attribute, the behavior is exactly what I want, except I have to disable the editing feature in element A.

<div contenteditable>element A</div>
<div>element B</div>

is there any other easier solution, like CSS only, that can solve it?

2

Answers


  1. If you only have text in your divs, then you could use disabled text inputs or text areas to achieve that behavior. Of course you would have to set the CSS to get the wanted appearance.

    With text inputs:

    input[type=text] {
      display: block;
      color: black;
      text-decoration: none;
      background: white;
      border: none;
    }
    <input type="text" value="element A" disabled/>
    <input type="text" value="element B" disabled/>

    With text areas:

    textarea {
      display: block;
      height: 15px;
      color: black;
      text-decoration: none;
      background: white;
      border: none;
      resize: none;
    }
    <textarea disabled>element A</textarea>
    <textarea disabled>element B</textarea>
    Login or Signup to reply.
  2. In future user-select: containsounds as though it will do want you want but as of today no one seems to have implemented it.

    A sort of solution would be to have a container set to user-select: none and then set an element to allow user-select when it has the cursor over it.

    <style>
      .container {
        user-select: none;
      }
      
      .container div:hover {
        user-select: text;
      }
    </style>
    <div class="container">
      <div>element A</div>
      <div>element B</div>
    </div>

    This will stop selection outside the element but (to me) it gives a slightly odd feeling when you stray outside the element, selecting part of that.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search