将文字放在图像上

时间:2010-02-16 19:14:07

标签: html css

我有这张图片:

enter image description here

但我想把文字放在中间,如下:

This is how i wanted.

我怎样才能做到这一点?

我想在html中执行此操作,因此我会使用<div><span>

4 个答案:

答案 0 :(得分:21)

使用伪元素

可以使用包含元素的::before::after伪元素创建上述内容。对于instnace,假设我们从这开始:

<h1>Keep Calm and Stack Overflow</h1>

我们可以定位两个伪元素,设置它们的尺寸和背景图像,并获得与上述相同的效果。

h1::before, h1::after {
    content: ""; display: block; height: 3em;
    background: url('ribbon.png') center center;
}

以上只是您可能写的内容的一个例子。有关更全面的演示,请参阅this fiddle

enter image description here

使用背景图像(原始2010答案)

创建一个div,它是图像的尺寸。然后将文本放在里面。在文本上使用边距/填充以使其垂直居中,并为其CSS设置text-align为“中心”。

.imgBox  { 
    width: 300px; height: 100px; 
    background-image: url('bg.jpg');
}
.imgText { 
    text-align: center; 
    margin: 0; padding: 25px 0 0 0;
}
<div class="imgBox">
  <p class="imgText">Hello World</p>
</div>

答案 1 :(得分:2)

您还可以使用绝对定位和z-index:

<img src="yourimagefile.jpg" class="background-image" />
<p class="overlay-text">Your Test</p>

在CSS文件中:

.background-image { z-index: -1; }
.overlay-text { position: absolute; top: ??px; left: ??px; }

一些不错的参考资料: http://www.w3schools.com/Css/pr_pos_z-index.asp

答案 2 :(得分:0)

对我来说,这看起来像<img>,然后是<span>中的一些文字,然后是第二个<img>。如果你将它们全部放入一个有text-align: center的容器中,一切都应该没问题。

答案 3 :(得分:0)

创建一个与图像宽度和高度相同的div,并使用css将图像设置为div的背景。将垂直对齐中间和水平对齐中心放在div上并将文本添加到其中。

相关问题