2014-07-04 223 views
2

我有一個奇怪的填充圖像和跨度之間,我無法擺脫。奇怪的填充圖像和跨度

<div> 
    <img src="http://placehold.it/100x100" /> 
    <span>hello</span> 
</div> 

img{ 
    padding:20px; 
    background: red; 
} 

span{ 
    width: 300px; 
    background-color: blue; 
    display: inline-block; 
    vertical-align: top; 
    height: 100%; 
} 

正如您在本fiddle看,我有紅色和藍色元素之間的一些空間。不管我做什麼,我都擺脫不了它。另外我會很感激有人可以告訴我爲什麼我的height: 100%;不適用於第二個元素(它應該與圖像高度相同)。

回答

6

由於html源文件中的<img><span>之間有一個空格,所以存在一個奇怪的填充。

<div> 
    <img src="http://placehold.it/100x100" /> 
    <span>hello</span> 
</div> 

卸下空間將消除填充。

<div> 
    <img src="http://placehold.it/100x100" /><span>hello</span> 
</div> 

但是,這可能不是你所追求的(閱讀)。根據你的第二個問題,100%不起作用的原因是因爲<div>沒有給出高度,並且沒有什麼可以將百分比高度作爲基礎。這裏的高度<div>是其內容高度的結果。它需要較高元素的高度,以便它可以同時適應兩者。

所以你實際上是在尋找的是display: table。使用表格很容易實現圖像和文本的並排放置。

div { 
    display: table; 
} 

img { 
    display: table-cell; 
    padding:20px; 
    background: red; 
} 

span { 
    display: table-cell; 
    width: 300px; 
    background-color: blue; 
    vertical-align: top; 
    height: 100%; 
} 

See demo here.

+0

它爲我工作,謝謝。 – SalutonMondo

1

內聯元素對空白區域很敏感。簡單地將其刪除:

<div> 
    <img src="http://placehold.it/100x100" /><span>hello</span> 
</div> 

jsFiddle example

或者

<div> 
    <img src="http://placehold.it/100x100" /><!-- 
    --><span>hello</span> 
</div> 

jsFiddle example

的另一種技術是使容器元件零上的字體大小,然後重置在孩子的大小,但我不知道這不推薦。

0

你的空間的原因是,你有元件之間的空間。只需刪除空間。

1

添加在圖像的CSS display:block

嘗試在fiddle

img{ 
    padding:20px; 
    background: red; 
    display:block; 
} 

span{ 
    width: 300px; 
    background-color: blue; 
    display: inline-block; 
    vertical-align: top; 
    height: 100%; 
} 
0

應用顯示屬性或float屬性爲您的IMG。因此,CSS將是這樣的:

img{ 
padding:20px; 
background: red; 
display:block; 
} 

或者

img{ 
padding:20px; 
background: red; 
float:left; 
}