CSS / 變更選取文字的背景顏色

CSS / 變更選取文字的背景顏色

在 CSS 當中有定義一些偽元素選擇器 (pseudo element selector),他是用兩個冒號 :: 表示指定元素的特定的狀態。例如下面這個 code 就表示所有段落 (p) 的第一行 (first-line)。

p::first-line {
    /* style */
}

那麼要怎麼改變被選取文字的背景色呢?
只需要使用 ::selection 這個偽元素就可以囉!

假設我們要改變所有段落中被選取的文字的背景色:

p::selection {
    background: #0ABAB5;
}

下面這段文字就應用了上面這段 CSS 屬性,被選取的文字背景色會是 #0ABAB5 這個顏色 (tiffany blue):

Our deepest fear

A Return to Love: Reflections on the Principles of “A Course in Miracles” — Marianne Williamson (1992)

Our deepest fear is not that we are inadequate. Our deepest fear is that we are powerful beyond measure. It is our light, not our darkness that most frightens us. We ask ourselves, Who am I to be brilliant, gorgeous, talented, fabulous? Actually, who are you not to be? You are a child of God. Your playing small does not serve the world. There is nothing enlightened about shrinking so that other people won’t feel insecure around you. We are all meant to shine, as children do. We were born to make manifest the glory of God that is within us. It’s not just in some of us; it’s in everyone. And as we let our own light shine, we unconsciously give other people permission to do the same. As we are liberated from our own fear, our presence automatically liberates others.

在本文撰寫時的測試,目前 Chrome、Firefox、Safari、Opera 都已經支援這個設定,而 IE 11 依然不支援此種效果。