htmlcssgoogle-chromefirefox

Why does Chrome select text from separate divs instead of the current div?


Consider the following html:

<div style="user-select:none;position:absolute;top:10px;border:1px solid gray;height:100px;width:150px">
    <div style="user-select:text;position:absolute;top:10px">One</div>
    <div style="user-select:text;position:absolute;top:30px">Two Three</div>
</div>

If I double click (or triple click) on the word Two, I would expect Two Three be selected - as these words are in the same div. But Chrome instead selects One and Two - words different divs. Safari also does this.

Firefox, on the other hand, does it correctly (in my opinion) and selects Two Three.

Is there a way to modify the behavior so that it selects words in its own div?

P.S. Video of the behavior side by side.


Solution

  • Add a tabular display type for child divs - display: table. This will prevent text selection in "neighboring" divs at absolute positioning.

    You can also use a flexible display type for this purpose - display: flex.

    div > div {
      display: table;
    }
    <div style="user-select:none;position:absolute;top:10px;border:1px solid gray;height:100px;width:150px">
        <div style="user-select:text;position:absolute;top:10px">One</div>
        <div style="user-select:text;position:absolute;top:30px">Two Three</div>
    </div>