2015-07-02 41 views
0

我有一組圖標,適用於酒店設施,我嘗試使用CSS精靈將它們顯示在我的頁面上。 這是我對HTML我無法讓我的css精靈顯示

<div class="sprite"> 
      <ul id="amenities"> 
       <li class="bathtub"></li> 
       <li class="shower"></li> 
       <li class="next"></li> 
       <li class="tv"></li> 
       <li class="safe"></li> 
      </ul> 
     </div>  

我的CSS

.amenities { position: relative; } 
.amenities li { margin: 0; padding: 0; list-style: none; position: absolute; top: 0; } 
.bathtub { background: url('graphics/icons.png') no-repeat 0 0; width: 60px; height: 60px;} 
.shower { background: url('graphics/icons.png') no-repeat -61 0; width: 60px; height: 60px;} 

只有第一個圖標顯示,第二個犯規。 jsfiddle

enter image description here

我怎麼需要它看起來

enter image description here

回答

1

您沒有設置任何單位在背景上的位置。將其設置爲任何類型的單位將使其工作。零是這個規則的一個例外。

shower { background: url('graphics/icons.png') no-repeat -61px 0; width: 60px; height: 60px;} 

參見:https://jsfiddle.net/kbrbc62h/

編輯: 針對你最近的評論,參見:https://jsfiddle.net/Ls8wLsa6/

元素,如鋰,UL,H *和DIV在默認情況下有一個display:block。這意味着這些元素將佔據整條線。我們可以設定一個指定的寬度,但即使這個容器仍然放在一個新的線上。通過將li元素更改爲使用內聯塊,我們可以將它們塞入到一行中。由於ul的寬度是固定的,因此每個第三個元素都會出現在一個新的行上。

我們使用vertical-align:top;將li內容對齊到容器的頂部,然後調整p標籤以在中間顯示文本,沒有空白。

HTML:

<div class="sprite"> 
    <ul id="amenities"> 
     <li><div class="bathtub"></div><p>Bath</p></li> 
     <li><div class="shower"></div><p>Shower</p></li> 
     <li><div class="kitchen"></div><p>Kitchen</p></li> 
     <li><div class="bathtub"></div><p>Bath</p></li> 
     <li><div class="shower"></div><p>Shower</p></li> 
     <li><div class="kitchen"></div><p>Kitchen</p></li> 
     <li><div class="bathtub"></div><p>Bath</p></li> 
     <li><div class="shower"></div><p>Shower</p></li> 
     <li><div class="kitchen"></div><p>Kitchen Long</p></li> 
    </ul> 
</div> 

CSS:

#amenities { 
    width:320px; 
} 

.bathtub { 
    background: url('http://i.stack.imgur.com/NdUbQ.png') no-repeat 0 0; width: 60px; height: 60px; 
} 
.shower { 
    background: url('http://i.stack.imgur.com/NdUbQ.png') no-repeat -61px 0; width: 60px; height: 60px; 
} 

.kitchen { 
    background: url('http://i.stack.imgur.com/NdUbQ.png') no-repeat -122px 0; width: 60px; height: 60px; 
} 

.sprite ul li { 
    list-style-type:none; 
    display:inline-block; 
    vertical-align:top; 
    margin:10px; 
    width: 60px; 
} 

.sprite ul li p { 
text-align:center; 
margin:0; 
} 
+0

謝謝@laughingpine。我需要第一排彼此相鄰,它們之間有20px的空間。我添加了我在初始文章中需要的圖像。這是我第一次與精靈合作。 – JFA

+0

看看編輯。我們可以通過調整列表的css來實現類似的功能。我鼓勵你玩弄新的小提琴。 – laughingpine