2017-03-07 76 views
9

我有一個POC,必須完成,並且只允許使用CSS來更新產品的樣式。我已經使用CSS內容屬性將產品圖片中的一幅圖片替換爲徽標。包含CSS內容的div,僞元素不可見後

我必須添加一個簡單的字符串,並在此徽標後顯示電話號碼。我試圖用:after僞元素來做到這一點。這僅適用於div爲空的內容(徽標已被刪除)。

.demo { 
 
    content: url('http://placehold.it/350x150') 
 
} 
 

 
.demo:after { 
 
    content: 'test'; 
 
    display: inline-block; 
 
}
<div class="demo"></div>

我曾試圖改變displayinline-block和硬編碼爲兩個規則的heightwidth。基本上我能找到的所有東西。任何幫助將不勝感激。

的jsfiddle這裏:https://jsfiddle.net/qykbjznm/

+0

可能的重複:http://stackoverflow.com/questions/6949148/css-after-not-adding-content-to-certain-elements – pzworks

+0

@pzworks:甚至沒有關閉。 – BoltClock

回答

13

content屬性替換元素中的所有內容。通過將content添加到非僞選擇器,該內容將替換::before::after僞選擇器。

因此,請僅使用::before::after僞選擇器中的content屬性嘗試執行此操作。

.demo:before { 
 
    content: url('http://placehold.it/350x150') 
 
} 
 

 
.demo:after { 
 
    content: 'some text'; 
 
    display: block; 
 
}
<div class="demo"></div>

+0

只是增加了解釋,'content'只能用於僞元素,即':before'和':after',所以對'.demo'使用'content'將會失敗。 –

+0

@ Mr.Alien如果你看看OP提供的JSfiddle,'content'被應用到一個非僞選擇器,並被渲染爲'content'在':: before' /':: after'之內,這是根他遇到的問題的原因。 – Jamy

+0

@Mr。外星人:更正,它只在*之前和之後支持*。某些瀏覽器會將內容應用於實際元素,但它被視爲非標準行爲。 – BoltClock

4

你可以從你的CSS更換背景,並把它作爲HTML的圖像:

.demo::after { 
 
    content: 'test'; 
 
    display: inline-block; 
 
}
<div class="demo"> 
 
    <img src='http://placehold.it/350x150'/> 
 
</div>

甚至做到這一點:

.demo { 
 
    background: url('http://placehold.it/350x150'); 
 
    height:150px; 
 
    width:350px; 
 
} 
 

 
.demo::after { 
 
    content: 'test'; 
 
}
<div class="demo"></div>

有兩種不同的結果。

0

我與你的jsfiddle周圍搞砸了一下,我發現,使得目前的div在電話號碼下方顯示的唯一途徑是通過創建另一個DIV:

<div class="demo"></div> 
<div class="demo2"></div> 
<style> 
    .demo { 
    content: url('http://placehold.it/350x150'); 
    height:150px; 
    width:350px; 
    } 

    .demo2:before { 
    content: "test"; 
    } 
</style> 
2

某些瀏覽器將content屬性應用於實際元素,儘管它的內容爲not being supported in CSS2。預計css-content-3允許這樣做,但是直到3級規範成爲標準,這在現實中將不會再發生幾年(特別是考慮到它在最近的年沒有發生),應用content到實際的元素應該被認爲是非標準的行爲。

content屬性的值是圖像時,that image is inserted as replaced content。並且,當它應用於實際元素時,這可以防止元素具有::before::after僞元素。這就是爲什麼你的::after僞元素沒有出現。

如前所述,您只需將圖像應用於元素的::before僞元素,而不是元素本身。