2010-12-22 103 views
0

我想在頁面上顯示圖像,但我不想在html中對圖像的引用進行硬編碼。如何僅使用css在html頁面上顯示圖像?

是否有可能做這樣的事情:

HTML:

<span id="got-easier"></span> 

CSS:

#got-easier { image: url(/i/trend-down.gif); } 

(IE6應予以支持)

+3

基於文件名和id,它看起來像圖像傳遞給用戶的信息,即它不是表示性的,不應該通過CSS添加,並且*應該*包含在帶``的元素中, `alt`屬性。 – Quentin 2010-12-22 09:57:55

回答

3

是,使用背景圖片:)

#got-easier { background-image: url(/i/trend-down.gif); } 

請記住設置跨度爲display: block;並設置圖像的寬度/高度(如果使用它)。

正如David Dorward所指出的,如果它是一個與信息相關的圖像,它應該包含在具有<img>標記和alt屬性的文檔中。

1

和雅,它的通用術語是css圖像替換技術(或IR)。以下是目前常用的方法。只要選擇任何兩個;)

/* Leahy Langridge Method */ 
span#imageName { 
    display: block; 
    height: 0 !important; 
    overflow: hidden; 
    padding-top: 0px; /* height of image */ 
    width: 0px; /* width of image */ 
    background: url(url/of/image.jpg) no-repeat 
} 

/* Phark Method */ 
span#imageName { 
    display: block; 
    width: 0px; 
    height: 0px; 
    background: url(url/of/image.jpg) no-repeat; 
    text-indent: -9999px 
} 
0

如果您想內嵌顯示圖像,位置:絕對的伎倆:

#got-easier { 
    display:inline; 
    position:absolute; 
    width:img-Xpx; 
    height:img-Ypx; 
    background:url(/i/trend-down.gif) no-repeat; 
} 

與此唯一的問題是,由於圖像位置是絕對的,它會覆蓋它旁邊的任何內容(在IE6中它可能會出現在後面),而我發現解決此問題的方法(包括CSS和jQuery)在IE6中不受支持。你的圖像容器將不得不緊跟着新的行。

例如,當您想在表單標題或按鈕旁邊放置(?)圖像(通常沒有任何旁邊的圖標)以顯示onmouseover幫助時,這可能會很有用。

相關問題