今天是第 9 天,因為前幾天寫了偽類,所以今天就順便來整理偽元素囉!
偽元素是在畫面上看起來有這個元素,但是實際上卻不是一個真的元素,不存在 DOM 節點中,但是可以設定它的 CSS 樣式,就像真的元素一樣。
偽元素是以兩個冒號 :: 為開頭,後面加上名稱,例如 p::first-line ,會選取到 <p> 的第一行。
雖然現在 CSS3 是以一個冒號表示偽類,兩個冒號表示偽元素來做區分,不過因為考量到相容性的關係,舊有 CSS2 與 CSS1 的 :first-line、:first-letter、:before、:after 還是可以使用,但是還是建議遵守新的規範喔!
目前的規範中,每個選擇器只能應用一個偽元素。如果想併用,需要寫兩次,例如 ::first-line 與 ::first-letter 一起使用 (example 1)。
::first-line::before 或 ::after,偽元素的 content 也會被包含在裡面::first-letter::before 或 ::after,偽元素的 content 也會被包含在裡面如果想要讓首行文字變藍色,首字也要放大,不能這樣寫,需要分開寫兩次
// 錯誤示範
.example1 p::first-line::first-letter {
color: blue;
line-height: 2;
font-size: 300%;
}
.example1 p::first-line {
color: blue;
line-height: 2;
}
.example1 p::first-letter {
font-size: 300%;
}

那如果我又在 <p> 增加了 ::before 和 ::after
.example1 p::before {
content: "123456789";
}
.example1 p::after {
content: "987654321";
}

可以看到偽元素的內容有算在裡面,變成 1 為首字
::before and ::after::marker.example2 ul li::marker {
content: "+ ";
color: brown;
}
.example2 ol ::marker {
color: purple;
}

可以看到水果清單從圓點變成加號
::selection.example3 p::selection {
background-color: green;
color: orange;
}

::placeholder<input>、<textarea> 元素::first-line 的
明天會再繼續整理 content 屬性的值
參考資料:
W3C - Pseudo-elements
W3schools - Pseudo-elements
MDN文章同步更新於 medium