【问题标题】:How to put text over images in html?如何在html中的图像上放置文本?
【发布时间】:2011-08-11 03:31:22
【问题描述】:

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

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

【问题讨论】:

  • 那是不正确的 HTML; img 是一个自闭合标签,如下所示:&lt;img src="example.jpg" alt="Alt text"&gt;(等效地,在 XHTML 中:&lt;img src="example.jpg" alt="Alt text" /&gt;)。

标签: html


【解决方案1】:

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

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

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

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

more here

注意:这会巧妙地篡改文档的语义。如果需要,使用 javascript 将 div 注入到真实图像的位置。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 虽然 Caspar 的解决方案运行良好,但我赞成这个解决方案,因为它可以很好地降级。
    【解决方案3】:

    &lt;img&gt; element is empty——它没有结束标签。

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

    【讨论】:

      【解决方案4】:

      你可以试试这个……

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

      【讨论】:

      • position: absolute; 可以解决问题,但却是响应速度的杀手
      【解决方案5】:

      使用absolute 作为position 不响应+移动友好。我建议将divbackground-image 一起使用,然后在div 中放置文本将在图像上放置文本。根据您的 html,您可能需要使用 heightvh

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-08
        • 2015-01-05
        • 1970-01-01
        • 2014-04-27
        • 2016-04-16
        • 2014-09-24
        相关资源
        最近更新 更多