首頁  >  文章  >  web前端  >  如何使用 CSS 變更選取文字的顏色?

如何使用 CSS 變更選取文字的顏色?

WBOY
WBOY轉載
2023-08-26 14:33:022931瀏覽

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

網站上的文字樣式是網頁設計和開發的一個重要面向。為此,CSS(層疊樣式表)是一個可供您使用的強大工具。 CSS 是一種多功能工具,允許以各種方式操縱文字的外觀。最受追捧的技術之一是更改所選文字的顏色。在本文中,我們將學習兩種使用 CSS 更改所選文字顏色的技術。

::選擇偽元素

::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 元素中選取文字的顏色變更為白色,並將選取文字的背景顏色變更為紅色。

範例

以下範例將選定的

文字顏色變更為白色,背景顏色變更為紅色,

文字變更為紅色,背景變更為黃色,

文字變更為藍色,背景顏色變更為粉紅色.

<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 偽元素來完成。透過使用顏色和背景顏色屬性,我們可以更改網站上所選文字的外觀。此外,我們可以在特定元素或類別上使用 ::selection 偽元素,以更精確地控制所選文字的樣式。

以上是如何使用 CSS 變更選取文字的顏色?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除