问题描述

如何在 HTML 中的图像上放置文本。每次输入以下代码时,文字都会在图像之下。

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

最佳解决方法

您需要在 relatively-positioned img 标签上使用 absolutely-positioned CSS 。文章 Text Blocks Over Image 给出了一个 step-by-step 示例,用于将文本放置在图像上。

次佳解决方法

<img> 元素是空的 – 它没有结束标签。

如果图像是 a background image, use CSS 。如果是内容图像,则在容器上设置 position: relative,然后将 absolutely position 设置为其中的图像和/或文本。

第三种解决方法

您可以创建与图像大小完全相同的 div 。

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

使用 css background-image 属性来显示图像

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

more here

注意:这样做会玷污你的文档的语义。如果需要,使用 javascript 将 div 注入到真实图像的位置。

第四种方法

你可以试试这个…

<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%; 
}

参考文献

注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。