僞類與僞元素,傻傻分不清楚。express
官方定義:瀏覽器
The pseudo-class concept is introduced to permit selection based on information that lies outside of the document tree or that cannot be expressed using the other simple selectors.bash
其核心就是用來選擇那些不可以被普通選擇器選擇的文檔以外的元素,好比:hover。ide
官方定義:post
Pseudo-elements create abstractions about the document tree beyond those specified by the document language. For instance, document languages do not offer mechanisms to access the first letter or first line of an element’s content. Pseudo-elements allow authors to refer to this otherwise inaccessible information. Pseudo-elements may also provide authors a way to refer to content that does not exist in the source document.this
其核心就是須要建立一般不存在於文檔中的元素,好比::before。spa
看了它們的定義應該對它們之間的異同有所瞭解了吧,呵呵 🙃🙃🙃...code
表示方法orm
CSS2 中僞類、僞元素都是以單冒號:
表示,CSS2.1 後規定僞類用單冒號表示,僞元素用雙冒號::
表示,瀏覽器一樣接受 CSS2 時代已經存在的僞元素(:before, :after, :first-line, :first-letter 等)的單冒號寫法。對於 CSS2 以後全部新增的僞元素(如::selection),應該採用雙冒號的寫法。可是由於兼容性問題,大部分仍是用的單冒號。ci
定義不一樣
僞類即假的類,一般能夠添加類來達到效果,僞元素即假元素,須要經過添加元素才能達到效果。來看下面的例子
例 1:將一行字符串的首字母變成紅色
如今不用僞元素應該如何實現?用 CSS slector 選擇?想了一夜也沒想出來,既然無法選擇也就無法添加一個類來改變首字母的顏色。
<p>I am snow</p>
複製代碼
添加元素試試,以下,建立一個元素 span 將首字母包裹起來,進而改變其顏色,成功了。這裏,關鍵點在於咱們建立了新的元素達到了::first-letter
的做用,且不能經過添加其餘類來實現這一效果,所以將::first-letter
叫作僞元素而不是僞類。
<p><span style={{ color: red }}>I<span/> am snow</p>
複製代碼
例 2: 以下要將 I am snow 這句話變爲紅色
很簡單用:first-child
,一樣添加一個類試試,顯然很容易達到一樣效果,咱們並無建立新的元素只是添加了一個類.red-line
,所以將:first-child
叫作僞類而不是僞元素,儘管它和::first-letter
在語義上十分類似。
div:first-child {
color: red;
}
或
.red-line {
color: red;
}
<div class='red-line'>
<p>I am snow</p>
<div>
複製代碼
:
和雙冒號::
來表示。關於經常使用的僞類與僞元素選擇器能夠查看CSS選擇器一文。