文字和背景颜色覆盖在图像上 [英] Text and background-color overlay on image

查看:258
本文介绍了文字和背景颜色覆盖在图像上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建与图像大小完全匹配的纯色覆盖层,并在该覆盖层上显示文本.如果可能的话,我只想使用HTML和CSS.

I'm trying to create a solid-color overlay that exactly matches the size of an image, and display text on that overlay. I'd like to do this with HTML and CSS only, if possible.

图像可以是任何大小,并且大小可以使其在其父容器中适合并居中.这样的东西(不起作用):

The image may be of any size, and will be sized to fit and centered within its parent container. Something like this (which does not work):

HTML:

<div class="img-overlay">
  <img src="file.jpg">
  <div class="overlay">Text will flow...</div>
</div>

CSS:

.img-overlay img {
  margin: 0 auto;
  max-height: 100%;
}
.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%
  background-color: rgba(255,255,255,0.5);
}

我认为HTML5的<figure>标记在这里可能会有所帮助,但是在这方面并没有取得太大的成功.以下内容使标题宽度与图像宽度保持一致,但是当我尝试将其从文档流中移除并将其放置在图像上方时,由于图像通过margin: 0 auto;居中,因此它最终到达图像的左侧. /p>

I thought that HTML5's <figure> tag might help here, but haven't had much success on that front. The following keeps the caption width pegged to the image width, but when I try to remove it from the document flow and position it over the image, it ends up to the left of the image due to the image centering via margin: 0 auto;.

<figure>
  <img src="file.jpg">
  <figcaption>Text will flow...</figcaption>
</figure>

推荐答案

我为您提供了一个示例. http://jsfiddle.net/kb3Kf/2/

I made an example for you. http://jsfiddle.net/kb3Kf/2/

缺少的主要内容是您给文本一个绝对位置,但没有给包装器一个相对位置,就像这样:

The main thing that was missing was that you gave the text an Absolute position but didn't give the wrapper a Relative one, like so:

.img-overlay
{
    position: relative;
}

这非常简单,您可以将其带到多个方向.告诉我那是否是你想要的.

It's really simple, you can take it to many directions. Tell me if that's what you wanted.

这篇关于文字和背景颜色覆盖在图像上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆