HTML/CSS How to prevent highlighting text from spanning entire width of page in google chrome

前端 未结 4 2019
孤街浪徒
孤街浪徒 2021-01-05 22:59

Basically when I use Google chrome and highlight text on some websites, the highlight spans the entire width of the browser rather than just highlighting the text. How can C

相关标签:
4条回答
  • 2021-01-05 23:28

    You can't alter the machanism of the highlighting algorithm. The highlight spans through paddings and margins, which is annoying sometimes. What you could do is prevent any text selection with CSS

    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -o-user-select: none;
    user-select: none;
    
    0 讨论(0)
  • 2021-01-05 23:31
    .content{
      display:inline-block;
    }
    

    http://jsfiddle.net/V7ahp/4/

    The solution by CherryFlavourPez, using float, would lead to further complication like the container won't stretch according to the float div inside.

    0 讨论(0)
  • 2021-01-05 23:35

    In your .css file use position: relative; in the the div section that will contain your text.

    0 讨论(0)
  • 2021-01-05 23:40

    The OCD part of me has wondered this as well: the only thing I've noticed (though this is by no means a comprehensive solution) is that floated elements exhibit the behaviour you're after. This Fiddle shows a live version (screenshot below) whereby the two divs are identical save that one has the declaration float: left;, which prevents text highlighting from spanning the entire page.

    If it's a big enough issue for you (though I'd say otherwise), you could float your main container to ensure that text highlighting is constrained to it. @solendil's "solution" seems to be massive overkill, introducing a huge usability flaw (how annoying to not be able to select text) for the sake of a minor visual annoyance.

    Text highlighting in Chrome

    Update: as per @AndreZS's answer, adding a position value other than the default static also restricts the text highlighting to that element (I think this behaviour has changed in the years since my original answer). It would take someone familiar with WebKit to explain what exactly is going on to trigger the desired behaviour: seems like something to do with the layout of an element and how it is being drawn.

    0 讨论(0)
提交回复
热议问题