Html 使用相对定位将文本覆盖在图像上

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7452258/
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 10:39:16  来源:igfitidea点击:

Text overlays over image using relative positioning

htmlcssimagecss-positionoverlay

提问by Water

I want to position a text overlaying an image. Below is my currently used code:

我想放置一个覆盖图像的文本。以下是我目前使用的代码:

<td width="10%">
  <img src="tempballoon.png" alt="balloon" style="z-index: -1" />
  <div style="position:relative;left:30px;top:-75px;font-size: 32px;display: none">
    Test
  </div>
</td>

My problem is, although the text is properly overlayed, the "space" it consumes in the <td>is still there! When I tried to replace the 'top' position in the <div>with 'margin-top', it also affects the <img>and so the <img>goes past the border of the <td>.

我的问题是,虽然文本被正确覆盖,但它消耗的“空间”<td>仍然存在!当我尝试<div>用 'margin-top'替换 'top' 位置时,它也会影响<img>,因此<img>越过<td>.

回答by Blender

You want position: absoluteand the containerto be relative:

你想要position: absolute容器relative

<td width="10%" style="position: relative;">
    <img src="tempballoon.png" alt="balloon"  style="z-index: -1"/>
    <div style="position:absolute;left:0px;top:0px;font-size: 32px;display: none">
      Test
    </div>
</td>

回答by CBRRacer

Why not set a div inside the TD set the image to the background of the div and the drop your text in the div?

为什么不在 TD 内设置一个 div 将图像设置为 div 的背景并将您的文本放在 div 中?

<td width="10%">
 <div style="background: transparent url("tempballoon.png") no-repeat left top; font-size: 32px;width: 100%; height: height:[height of image]">
  Test
 </div>
</td>