css - 扩展所选文本的背景色矩形

标签 css

根据 MDN,大纲应该在 ::selection 伪元素上工作,但在 chrome 和 ff 上测试时似乎没有。

::selection {
  background-color:red;
  outline:2px dashed blue;
}
My cool text, select me!

我正在创建一个文本编辑器,基本上它只是让我烦恼选择背景颜色是多么紧密。我想将它扩展几个像素,轮廓将是该作业的正确属性,但它不起作用?

最佳答案

我认为 MDN 有误或未更新,因为如果我们引用 the specification :

The highlight pseudo-elements can only be styled by a limited set of properties that do not affect layout. The following properties apply to the highlight pseudo-elements:

  • color
  • background-color
  • cursor
  • caret-color
  • text-decoration and its associated properties
  • text-shadow
  • stroke-color, fill-color, and stroke-width

大纲 未列出,这解释了为什么它不起作用。此外,我认为您无法控制突出显示区域。如同一规范中所述:

For text, the corresponding overlay must cover at least the entire em box and may extend further above/below the em box to the line box edges. Spacing between two characters may also be part of the overlay area, in which case it belongs to the innermost element that contains both characters and is selected when both characters are selected.

我们已经有了 em 框,这是微不足道的,你最好的运气是拥有更多,以防线框更高,但它不会在跨浏览器中表现相同。

这是一个基本示例,其中我使用具有较大字体大小的伪元素来增加行框的高度,并将其居中对齐。在这种情况下,选择将覆盖超过文本,但当然这也会影响可能不需要的布局,并且不适用于所有浏览器。

以下示例适用于 Chrome 而不适用于 Fiferfox

p:after {
  content: "";
  font-size: 30px;
  vertical-align: middle;
}

p::selection {
  background-color: red;
}
<p>My cool text, select me!</p>

另一件重要的事情是,在该区域内应用的所有属性都不能溢出它。我们知道使用 text-shadow 我们可以将阴影放置在离文本很远的地方,但是选择它是不可能的,因为它不能溢出高亮区域:

p {
  text-shadow:0 10px 0 red;
}

p::selection {
  background-color: red;
  text-shadow:0 -10px 0 blue;
}
<p>My cool text, select me!</p>

注意蓝色文本阴影是如何部分可见的,就像我们将 overflow:hidden 应用于红色区域一样。因此,即使您能够使用轮廓设置选区的样式,也基本上不可能控制其尺寸,而这正是您在这里所需要的。


我认为你最好的选择是依靠 JS 来创建动态元素或包装选定的文本以轻松地设置它们的样式。使用 CSS,您只能应用一些会影响您的布局的 hack。

关于css - 扩展所选文本的背景色矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54741166/

相关文章:

html - IE11 flex child 不会收缩以给其他具有非包装内容的 child 留出空间

html - 使用 float 后的 CSS 定位

css - webkit 浏览器中用于渐变的背景图像 CSS

css - CSS 自定义属性是否可以包含多个要引用的值?

html - td 内的图像是 td 的高度

CSS 图像未显示在页面上

html - 卷轴从哪里来?

javascript - keyup 函数突出显示正在输入的值

html - 从一行中的第一个和最后一个元素中删除填充

html - Div 内容宽度(溢出问题)