2011-04-22 94 views
39

如何将文本放在HTML中的图像上。每次我输入下面的代码时,文本都会显示在图像下方。如何将文字放在html图片上?

<img src="example.jpg">Text</img> 
+1

即HTML不当; 'img'是一个自闭标签,如下所示:'Alt text'(等价地,在XHTML中:'Alt text')。 – mc10 2011-04-22 18:28:26

回答

22

您需要在相对定位的img标记上使用绝对定位的CSS。文章Text Blocks Over Image提供了将文本放置在图像上的分步示例。

+0

虽然卡斯帕的解决方案工作得很好,但我已经对此进行了升级,因为它的降级很好。 – 2011-04-22 18:36:13

19

您可以创建一个与图像尺寸完全相同的div。

<div class="imageContainer">Some Text</div> 

使用的CSS背景图像属性来显示图像

.imageContainer { 
     width:200px; 
     height:200px; 
     background-image: url(locationoftheimage); 
} 

more here

注:此slichtly篡改文档的语义。如果需要使用javascript将div注入到真实图像的位置。

12

你可以试试这个...

<div class="image"> 

     <img src="" alt="" /> 

     <h2>Text you want to display over the image</h2> 

</div> 

CSS

.image { 
    position: relative; 
    width: 100%; /* for IE 6 */ 
} 

h2 { 
    position: absolute; 
    top: 200px; 
    left: 0; 
    width: 100%; 
} 
+0

4.5年后,仍然鼓舞人心! – Burak 2017-10-28 17:35:55