IMG標籤與before,after僞類

在CSS中總有一些你不用不知道,用到才知道的“坑”。比如今天要談的,把 before, after 僞類用在 <img> 標籤上。
嗯,實際上你用你會發現,在大多數瀏覽器這是無效的,dom中並不會出現你想要的結果。
爲什麼會這樣呢?
讓我們迴歸到 W3C 標準中尋覓一下,在標準中,before, after 僞類的定義如:

As their names indicate, the :before and :after pseudo-elements specify the location of content before and after an element's document tree content.
來自 https://www.w3.org/TR/CSS21/generate.html#before-after-content

我們應該注意到所謂 document tree content,對於 img 這種自閉和標籤,似乎不存在 content (內容或後代元素)在標籤中,所以選擇器沒有生效。但這樣的解釋還不夠清晰,實際上標準中還有一行註釋:

Note. This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.

嗯,這回清楚了,對於可替換元素(如 img、input、select 等),標準並沒有清晰定義,這也導致了瀏覽器實現的差異性。
有解決辦法麼?搜了一下是有的(http://stackoverflow.com/questions/5843035/does-before-not-work-on-img-elements):

  1. 使用jQuery

    使用 jQuery 的 before,after 方法:

    javascript
    $('.target').after('<img src="..." />');


    實際上,jQuery 只是在目標元素前後插入 dom 而已。

  2. 僞造 content

給 img 這類標籤添加 content 屬性,輸入一些無意義的文本,讓瀏覽器認爲標籤含有 content。
如在 CSS 中添加:

css
img {
/ hide the default image /
height:0;
width:0;
/ hide fake content /
font-size:0;
color:transparent;
/ enable absolute position for pseudo elements /
position:relative;
/ and this is just fake content /
content:"I'm just fake content";
}


但這種方法存在瀏覽器兼容問題。

所以最後還是建議不要做這種嘗試了,給父標籤添加僞類吧。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章