2010-08-16 37 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: ____;属性。