2010-08-16 44 views
4

我想顯示浮動圖像下面有一個標題。但是使用下面的代碼,標題文本不會換行,這意味着浮動的帶圖像的標題佔據了一個huuuuge的水平空間。浮動文本內部的文本

如果有一個更好的方式來讓圖片帶有標題,我會對此代碼進行任何改進。如果不這樣做,我怎麼才能讓浮動內部的文本包裝?

我試過尋找這個,但只能得到包圍文本週圍的浮動,不在裏面的結果。

添加:我不希望爲float設置明確的寬度,因爲我必須爲每個使用的圖像都這樣做。

完整的XHTML ...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr"> 

<head> 
<title>Test</title> 

<style type="text/css"> 

p.img-with-cap { 
    float: left; 
} 

</style> 


</head> 

<body> 

<p class="img-with-cap"> 
<a class="img" href="http://sohowww.nascom.nasa.gov/"> 
<img alt="Sun" src="http://www.heeris.id.au/sites/default/files/sun.gif" width="256" height="256" /> 
</a> 
<br />The Sun - a sinister and destructive force. Image from 
<a href="http://sohowww.nascom.nasa.gov/">SOHO website</a>. 
</p> 

<p style="font-size: 200%">The Sun is a star located at the centre of our solar system. It is 
classified as a G2 star, has a mass of about 2×1030 kg, a temperature of 
5800 K at the surface and a core temperature of 15.6 million Kelvin. It 
constantly emits electromagnetic radiation over the entire spectrum 
(indeed, it can be modelled as a black body), peaked at the wavelength 
corresponding to that of green light.</p> 

</body> 

</html> 

回答

2

塊級浮動元素可以應用於它們的寬度。我會想象下面的樣式應防止包裝:

p.img-with-cap { 
    float: left; 
    width: 200px; /* or whatever */ 
} 

如果你不想要一個特定的寬度,但希望它匹配圖像的寬度,可以動態地設置寬度窗口加載時,像這樣:

function setWidth() { 
    var width = document.getElementById("imgElement").width; 
    document.getElementById("wrapperElement").style.width = width; 
} 

window.onload = setWidth; 
+0

不是設置寬度的粉絲(查看更新後的問題)。那麼真的沒有一個通用的方法來做到這一點? – detly 2010-08-16 13:53:28

+0

我可以看到的最佳選擇是在圖像加載後通過javascript設置寬度(您可能希望將寬度設置爲合理的初始值)。我會更新我的答案。 – 2010-08-16 13:57:40

+0

這不是一個壞主意。我覺得有點奇怪,這樣一個明顯的用例不被CSS覆蓋,但我相信這不是第一次有人這樣說。 – detly 2010-08-16 14:07:39

1

浮動元素,就像任何其他塊元素,會佔用必要以適應其內容儘可能多的寬度 - 高達100%。

如果你想要它比100%窄,給它一個width: ____;屬性。