詳解CSS 偽元素及Content 屬性

初識偽元素
說起偽元素我第一想到的莫過于::before和::after這兩個了,它倆其實就是在其附屬的選擇器命中的元素上插入第一個子節(jié)點和追加最后一個子節(jié)點。那這時我不禁地想問:“直接添加兩個class為.before和.after不是一樣的嗎?” 其實使用偽元素::before和::after以下兩個好處:
1.HTML的代碼量減少,對SEO有幫助;
2.提高JavaScript查詢元素的效率。
那為什么會這兩好處呢?原因就是偽元素并不存在于DOM中,而是位于CSSOM,HTML代碼和DOM Tree中均沒有它的身影,量少了自然效率有所提升。但這也引入一個問題——我們沒辦法通過JavaScript完全操控偽元素(我將在下面一節(jié)為大家講述)
一大波偽元素來了
除了::before和::after外,別漏了以下的哦!
1.:first-line:只能用于塊級元素。用于設置附屬元素的第一個行內(nèi)容的樣式。可用的CSS屬性為font,color,background,word-spacing,letter-spacing,text-decoration,vertical-align,text-transform,line-height,clear。
2.:first-letter:只能用于塊級元素。用于設置附屬元素的第一個字母的樣式??捎玫腃SS屬性為font,color,background,marin,padding,border,text-decoration,vertical-align,text-transform,line-height,float,clear。
3.::selection:匹配選中部分的內(nèi)容??捎玫腃SS屬性為background,color。
有沒有發(fā)現(xiàn)有的偽元素前綴是:有的卻是::呢?::是CSS3的寫法,其實除了::selection外,其他偽元素既兩種前綴都是可以的,為兼容性可選擇使用:,為容易區(qū)分偽元素和偽類則使用::,但我還是建議使用::來提高可讀性,兼容性就讓postcss等工具幫我們處理就好了。
::before和::after的注意事項
1.默認display: inline;
2.必須設置content屬性,否則一切都是無用功;
3.默認user-select: none,就是::before和::after的內(nèi)容無法被用戶選中的;
4.偽元素和偽類結合使用形如:.target:hover::after。
JavaScript操作偽元素
上文提到由于偽元素僅位于CSSOM中,因此我們僅能通過操作CSSOM API——window.getComputedStyle來讀取偽元素的樣式信息,注意:我們能做的就是讀取,無法設置的哦!
{- window.getComputedStyle的類型 -} data PseudoElement = ":before" | "::before" | ":after" | "::after" | ":first-line" | "::first-line" | ":first-letter" | "::first-letter" | "::selection" | ":backdrop" | "::backdrop" | Null
window.getComputedStyle :: HTMLElement -> PesudoElement -> CSSStyleDeclaration
{- CSSStyleDeclaration實例的方法 -} data CSSPropertyName = "float" | "backround-color" | ...... data DOMPropertyName = "cssFloat" | "styleFloat" | "backgroundColor" | ......
-- IE9+的方法 CSSStyleDeclaration#getPropertyValue :: CSSPropertyName -> * -- IE6~8的方法 CSSStyleDeclaration#getAttribute :: CSSPropertyName -> * -- 鍵值對方式獲取 CSSStyleDeclaration#[DOMPropertyName] -> *
示例:
.target[title="hello world"]::after{ display: inline-block; content: attr(title); background: red; text-decoration: underline; } const elTarget = document.querySelector(".target") const computedStyle = window.getComputedStyle(elTarget, "::after") const content = computedStyle.getPropertyValue("content") const bg = computedStyle.getAttribute("backgroundColor") const txtDecoration = computedStyle["text-decoration"] console.log(content) // "hello world" console.log(bg) // red console.log(txtDecoration) // underline
玩透Content屬性
到這里我們已經(jīng)可以利用::before和::after實現(xiàn)tooltip等效果了,但其實更為強大的且更需花時間研究的才剛要開始呢!那就是Content屬性,不僅僅可以簡單直接地設置一個字符串作為偽元素的內(nèi)容,它還具備一定限度的編程能力,就如上面attr(title)那樣,以其附屬元素的title特性作為content值。下面請允許我為大家介紹吧!
div::after{ content: "普通字符串"; content: attr(父元素的html屬性名稱); content: url(圖片、音頻、視頻等資源的url); /* 使用unicode字符集,采用4位16進制編碼 * 但不同的瀏覽器顯示存在差異,而且移動端識別度更差 */ content: "\21e0"; /* content的多個值可以任意組合,各部分通過空格分隔 */ content: "'" attr(title) "'"; /* 自增計數(shù)器,用于插入數(shù)字/字母/羅馬數(shù)字編號 * counter-reset: [<identifier> <integer>?]+,必選,用于標識自增計數(shù)器的作用范圍,<identifier>為自定義名稱,<integer>為起始編號默認為0。 * counter-increment: [<identifier> <integer>?]+,用于標識計數(shù)器與實際關聯(lián)的范圍,<identifier>為counter-reset中的自定義名稱,<integer>為步長默認為1。 * <list-style-type>: disc | circle | square | decimal | decimal-leading-zero | lower-roman | upper-roman | lower-greek | lower-latin | upper-latin | armenian | georgian | lower-alpha | upper-alpha */ content: counter(<identifier>, <list-style-type>); /* 以父附屬元素的qutoes值作為content的值 */ content: open-quote | close-quote | no-open-quote | no-close-quote; }
換行符:HTML實體為
,CSS為\A,JS為\uA。
可以看到Content接受6種類型,和一種組合方式。其中最后兩種比較復雜,我們后面逐一說明。
自定義計數(shù)器
HTML為我們提供ul或ol和li來實現(xiàn)列表,但如果我們希望實現(xiàn)更為可性化的列表,那么該如何處理呢?content屬性的counter類型值就能幫到我們。
<!-- HTML 部分--> .dl .dt{chapter1} .dd{text11} .dd{text12} .dt{chapter2} .dd{text21} /* CSS部分 */ .dl { counter-reset: dt 0; /* 表示解析到.dl時,重置dt計數(shù)器為0 */ & .dt { counter-reset: dd 0; /* 表示解析到.dt時,重置dd計數(shù)器為0 */ &::before{ counter-increment: dt 1; /* 表示解析到.dt時,dt計數(shù)器自增1 */ content: counter(dt, lower-roman) " "; } } & .dd::before { counter-increment: dd 1; /* 表示解析到.dd時,dd計數(shù)器自增1 */ content: counter(dd) " "; } }
通過counter-reset來定義和重置計數(shù)器,通過counter-increment
來增加計數(shù)器的值,然后通過counter來決定使用哪個計數(shù)器,并指定使用哪種樣式。
如果用JavaScript來表示應該是這樣的
const globalCounters = {"__temp":{}} function resetCounter(name, value){ globalCounters[name] = value } function incrementCounter(name, step){ const oVal = globalCounters[name] if (oVal){ globalCounters[name] = oVal + step } else{ globalCounters.__temp[name] = step } } function counter(name, style){ return globalCounters[name] || globalCounters.__temp[name] } function applyCSS(mount){ const clz = mount.className if (clz == "dl"){ resetCounter("dt", 0) const children = mount.children for (let i = 0; i < children.length; ++i){ applyCSS(children[i]) } } else if (clz == "dt"){ resetCounter("dd", 0) incrementCounter("dt", 1) const elAsBefore = document.createElement("span") elAsBefore.textContent = counter("dt", "lower-roman") + " " mount.insertBefore(mount.firstChild) } else if (clz == "dd"){ incrementCounter("dd", 1) const elAsBefore = document.createElement("span") elAsBefore.textContent = counter("dd", "lower-roman") + " " mount.insertBefore(mount.firstChild) } }
嵌套計數(shù)器
對于多層嵌套計數(shù)器我們可以使用counters(<identifier>, <separator>, <list-style-type>?)
.ol .li .ol .li{a} .li .li .ol .li{c} .ol { counter-reset: ol; & .li::before { counter-increment: ol; content: counters(ol, "."); } }
Content的限制
1.IE8+才支持Content屬性;
2.除了Opera9.5+中所有元素均支持外,其他瀏覽器僅能用于:before,:after內(nèi)使用;
3.無法通過JS獲取Counter和Counters的運算結果。得到的就只能是"counter(mycouonter) \" \""。
自定義引號
引號這個平時很少在意的符號,其實在不同的文化中使用的引號將不盡相同,如簡體中文地區(qū)使用的"",而日本則使用「」。那我們根據(jù)需求自定義引號呢?答案是肯定的。
通過open-quote,close-quote,no-open-quote
和no-close-quote
即可實現(xiàn),下面我們通過例子來理解。
<q>會根據(jù)父元素的lang屬性自動創(chuàng)建::before和::after來實現(xiàn)插入quotation marks。
p[lang=en]>q{英語} p[lang=no]>q{挪威語} p[lang=zh]>q{漢語} p[lang=en]>q.no-quote{英語2} div[lang=no]>.quote{挪威語2}
CSS片段:
p[lang=en] > q{ quotes: "<!--" "-->"; /* 定義引號 */ } p[lang=en] > q.no-quote::before{ content: no-open-quote; /*或者 content: none;*/ } div[lang=no] > .quote { quotes: "<<-" "->>"; } div[lang=no] > .quote::before { content: open-quote; } div[lang=no] > .quote::after { content: close-quote; }
示例
分割線
p.sep{or} .sep { position: relative; text-align: center; &::before, &::after { content: ""; box-sizing: border-box; height: 1px; width: 50%; border-left: 3em solid transparent; border-right: 3em solid transparent; position: absolute; top: 50%; } &::before { left: 0; } &::after { right: 0; } }
只讀效果(通過遮罩原來的元素實現(xiàn))
.input-group { position: relative; &.readonly::before { content: ""; position: absolute; width: 100%; height: 100%; top: 0; left: 0; } }
計數(shù)器
.selections>input[type=checkbox]{option1}+input[type=checkbox]{option2} .selection-count .selections{ counter-reset: selection-count; & input:checked { counter-increment: selection-count; } } .selection-count::before { content: counter(selection-count); }
參考
http://www.wozhuye.com/compatible/297.html https://dev.opera.com/articles/css-generated-content-techniques/
總結
以上所述是小編給大家介紹的CSS 偽元素及Content 屬性 ,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
- 本篇重點介紹CSS中的:befor、:after創(chuàng)建的偽元素幾種使用場景,如填充文本、作為iconfont、進度線、時間線以及幾何圖形,感興趣的朋友一起看看吧2018-02-07
利用CSS3偽元素實現(xiàn)逐漸發(fā)光的方格邊框
這篇文章主要給大家介紹了利用CSS3偽元素實現(xiàn)逐漸發(fā)光的方格邊框的相關資料,文中給出了詳細的示例代碼供大家參考學習,對大家具有一定的參考學習價值,需要的朋友們下面來2017-05-07css3+偽元素實現(xiàn)鼠標移入時下劃線向兩邊展開的效果
這篇文章主要介紹了利用css3+偽元素實現(xiàn)鼠標移入時下劃線向兩邊展開效果的相關資料,文中先進行了詳細的介紹,方便大家理解,而后給出了完整的實例代碼讓大家可以參考學習2017-04-25CSS使用placeholder-shown偽類實現(xiàn)輸入框浮動文字效果
這篇文章主要介紹了CSS使用placeholder-shown偽類實現(xiàn)輸入框浮動文字效果,需要的朋友可以參考下2019-06-12- 本文通過圖文并茂的形式給大家介紹了CSS浮動與清除浮動的實例代碼,非常不錯,具有一定的參考借鑒價值,,需要的朋友可以參考下2019-04-29
- 這篇文章主要介紹了css 如何清除浮動的示例代碼,詳細的介紹了浮動到底是什么和清理浮動的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看2018-11-12
- 這篇文章主要介紹了css 盒模型 文檔流 幾種清除浮動的方法實例詳解,需要的朋友可以參考下2018-09-10
- 這篇文章主要介紹了css布局之定位與浮動的相關資料,需要的朋友可以參考下2018-05-21
- 使元素脫離文檔流,按照指定方向發(fā)生移動,遇到父級邊界或者相鄰的浮動元素停了下來。本文給大家?guī)砹薈SS清除浮動float的三種方法小結,感興趣的朋友跟隨腳本之家小編一起2018-03-13
- 塊級格式化上下文,是一個獨立的渲染區(qū)域,讓處于 BFC 內(nèi)部的元素與外部的元素相互隔離,使內(nèi)外元素的定位不會相互影響。這篇文章給大家介紹了CSS 使用偽元素清除浮動的方2019-07-01