標籤:

為什麼input不支持偽元素(:after,:before)?

用input[type=submit]:after去添加內容沒有效果出來的


規範特么很含蓄的說道:

Authors specify the style and location of generated content with the :before and :after pseudo-elements. As their names indicate, the :before and :after pseudo-elements specify the location of content before and after an element"s document tree content. The "content" property, in conjunction with these pseudo-elements, specifies what is inserted.

http://www.w3.org/TR/CSS21/generate.html#before-after-content

作者用:before和:after偽元素指定生成的內容的樣式和位置。如其名所示,:before和:after偽元素指定了一個元素文檔樹內容之前和之後的內容。"content"屬性,與這些偽元素聯用,指定了插入的內容。

以我淺顯的理解來看,「一個元素文檔樹內容之前和之後的內容」就是指這個元素是要可以插入內容的,也就是說這個元素要是一個容器。

input,img,iframe等元素都不能包含其他元素,所以不能通過偽元素插入內容。至於Chrome 中checkbox和radio可以插入,那應該是Bug了,要麼就是姿勢不對了。

詳見Demo: http://jsbin.com/gixuveqo/1/edit

2016-03-10 更新

Blink 意圖刪除 input 中插入偽元素的功能:https://bugs.chromium.org/p/chromium/issues/detail?id=480891

補充一下原因:

According to the pseudo-elements spec(http://dev.w3.org/csswg/css-pseudo-4/#generated-content) pseudo-elements like ::before and ::after generate boxes as if they were immediate children of their originating element. And the HTML5 spec(http://www.w3.org/TR/html5/forms.html#the-input-element) says that the content model of & elements is empty, so they don"t have any children. In which case ::before and ::after pseudo-elements don"t apply to them.

We have already UseCounted the feature and now intend to show deprecation warning until M53 at least and decide on further action regarding removal for M54.


是的。作為DOM元素,偽元素都是在容器內進行渲染的。input無法容納其他元素,因此它不支持偽元素。按鈕也是在其他元素的支持下才由瀏覽器呈現出來的。W3C官方說明裡可以找到相關表述:

Authors specify the style and location of generated content with the
:before and :after pseudo-elements. As their names indicate, the :before
and :after pseudo-elements specify the location of content before and
after an element"s document tree content. The "content" property, in
conjunction with these pseudo-elements, specifies what is inserted.

http://www.w3.org/TR/CSS2/generate.html#before-after-content


的確如此,input要配合其它容器元素(i,span)等實現預期效果


這點相當坑爹,要通過before、after加額外樣式時,就得先套個div。。我去,


推薦閱讀:

CSS sprites 的樣式生成工具哪裡有?
CSS 3 中 -webkit-, -moz-, -o-, -ms- 這些私有前綴什麼時候可以移除?
css3的transition是直接寫在選擇器上,還是寫在選擇器的hover上,為什麼?
把 HTML5 簡稱為 H5 的人,會把 CSS3 說成 C3 嗎?
JS如何獲取CSS3的transform的值,style.tramsform無效呀?

TAG:CSS3 |