Html 如何将文本放在html中的图像上?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5758642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 08:10:20  来源:igfitidea点击:

How to put text over images in html?

html

提问by user719813

How to put text over images in HTML. Everytime I enter the below code, the text goes under the image.

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

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

回答by Caspar Kleijne

You can create a div with the exact same size as the image.

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

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

use the css background-image property to show the image

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

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

more here

更多在这里

note: this slichtly tampers the semantics of your document. If needed use javascript to inject the div in the place of a real image.

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

回答by kevinji

You need to use absolutely-positioned CSS over a relatively-positioned imgtag. The article Text Blocks Over Imagegives a step-by-step example for placing text over an image.

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

回答by Quentin

The <img>element is empty— it doesn't have an end tag.

<img>元素是空的-它没有结束标记。

If the image is a background image, use CSS. If it is a content image, then set position: relativeon a container, then absolutely positionthe image and/or text within it.

如果图像是背景图像,请使用 CSS。如果它是内容图像,则设置position: relative在容器上,然后将图像和/或文本绝对定位在其中。

回答by JIT1986

You can try this...

你可以试试这个...

<div class="image">

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

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

</div>

CSS

CSS

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

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

回答by deanwilliammills

Using absoluteas positionis not responsive + mobile friendly. I would suggest using a divwith a background-imageand then placing text in the divwill place text over the image. Depending on your html, you might need to use heightwith vhvalue

使用absoluteasposition不响应 + 移动友好。我建议使用 adiv和 abackground-image然后将文本放在div将文本放在图像上。根据您的 html,您可能需要使用heightwith vhvalue