如何使用 CSS 更改选定文本的颜色?

cssweb developmentfront end technology更新于 2025/3/9 20:28:17

网站上的文本样式是网页设计和开发中至关重要的环节。为此,CSS(层叠样式表)是一个强大的工具。CSS 是一个多功能的工具,允许以各种方式操控文本的外观。其中最受追捧的技术之一是更改选定文本的颜色。在本文中,我们将学习两种使用 CSS 更改选定文本颜色的技术。

::selection 伪元素

::selection 伪元素是一个强大的功能,它使我们能够选择并设置当前用户突出显示的文本的样式。要更改选定文本的颜色,我们使用 color 属性。例如,如果我们想让选定文本显示为栗色,我们将使用以下 CSS -

::selection {
    color: red;
}

这会将整个网页中选定文本的颜色更改为红色。

示例

以下示例将选定文本的颜色更改为红色,背景颜色更改为黑色。

<html >
<head>
   <title>Change the color of selected text using CSS?</title>
   <style>
      ::selection {
         color: red;
         background-color:black;
      }
   </style>
</head>
<body>
   <h2>Changing the color of selected text using CSS</h2>
   <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
   Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an 
   unknown printer took a galley of type and scrambled it to make a type specimen book.
   It has survived not only five centuries, but also the leap into electronic typesetting</p>
</body>
</html>

通过使用特定元素或类

我们可以更改特定元素或类上选定文本的颜色和背景颜色。例如,我们可以使用以下 CSS 更改特定"h1"标签内选定文本的颜色 -

h1::selection {
    background: red;
    color: white;
}

这会将 h1 元素内选定文本的颜色更改为白色,并将选定文本的背景颜色更改为红色。

示例

以下示例将选定的 <h1> 文本的颜色更改为白色,背景颜色更改为红色;将 <h2> 文本的颜色更改为红色,背景颜色更改为黄色;将 <p> 文本的颜色更改为蓝色,背景颜色更改为粉色。

<html>
   <title>Change the color of selected text using CSS</title>
   <style>
      h1::selection {
         background: red;
         color: white;
      }
      h2::selection {
         background: yellow;
         color: red;
      }
      p::selection {
         background: pink;
         color: blue;
      }
   </style>
</head>
<body>
   <h1>Welcome to tutorialsPoint</h1>
   <h2>Change the color of selected text using CSS</h2>
   <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
   Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown 
   printer took a galley of type and scrambled it to make a type specimen book. It has survived 
   not only five centuries, but also the leap into electronic typesetting</p>
</body>
</html>

结论

使用 CSS 更改选定文本的颜色非常简单,只需使用 ::selection 伪元素即可完成。通过使用 color 和 background-color 属性,我们可以改变网站上选定文本的外观。此外,我们还可以在特定元素或类上使用 ::selection 伪元素,以便更精确地控制选定文本的样式。


相关文章


有用资源