css中偽類和偽元素的區(qū)別

用處

普通基于元素或基于類的樣式定義像這樣

p {
color: red;
text-align: center;
}
這樣

para1 {

text-align: center;
color: red;

}
或這樣

.center {
text-align: center;
color: red;
}
可以看到他們都基于html dom樹中具體的類,或者元素進行樣式定義 ,但如果想對諸如元素狀態(tài)變化或位置進行樣式定義則需要用到偽類(Pseudo Classes)和偽元素(Pseudo Elements)。比如對一個連接訪問后其字體顯示方式,一個段落第一句話的顏色字體顯示方式等時候我們就需要用到偽類和偽元素了。

定義

顧名思義,偽類和偽元素不是真正意義上的html存在的類和元素,他們的存在是為了方便對狀態(tài)和位置進行樣式定義。

偽元素
對html中真實元素不同位置的指代。一般以兩個冒號作為開始,具體語法為:

selector::pseudo-element {
property:value;
}

selector.class::pseudo-element {
property:value;
}
示例:定義p元素中內(nèi)容的第一行為紅色小字

p::first-line {
color: #ff0000;
font-variant: small-caps;
}
偽類
對html中物理存在的元素進行動作操作后的狀態(tài)指代(比如點擊后,鼠標(biāo)移動上面后等),一般以一個冒號做為開始。具體語法如下:

selector:pseudo-class {
property:value;
}

selector.class:pseudo-class {
property:value;
}
示例:定義一個鏈接訪問過后的顏色

a:visited {
color: #00FF00;
}
全家福

css中可以使用的偽類以及偽元素全家福如下:

Selector Example Example description
:link a:link Selects all unvisited links
:visited a:visited Selects all visited links
:active a:active Selects the active link
:hover a:hover Selects links on mouse over
:focus input:focus Selects the input element which has focus
::first-letter p::first-letter Selects the first letter of every <p> element
::first-line p::first-line Selects the first line of every <p> element
:first-child p:first-child Selects every <p> elements that is the first child of its parent
::before p::before Insert content before every <p> element
::after p::after Insert content after every <p> element
:lang(language) p:lang(it) Selects every <p> element with a lang attribute value starting with "it"

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容