在Img上覆盖Figcaption

时间:2016-01-26 17:06:05

标签: html css image

我经营一个网站,我正在尝试将版权信息添加到图片的左上角。 img元素为float:left;figcaption元素位于img元素之后,但我遇到了一些问题:

1)如果我在position:absolute元素上使用figcaption CSS样式,它会覆盖图像上的标题,就像我想要的那样。但是,如果我一个接一个地列出多个图像,则字幕不再位于左上角,可能位于页面上的随机位置。enter image description here

2)如果我在position:relative元素上使用figcaption CSS样式,它会将标题放在图像旁边。当我将left:-410px;添加到figcaption CSS时,可以修复此问题,因为所有图像的宽度都相同。但是,设置为p元素旁边的img元素会在figcaption最初定位时留下空白。enter image description here

我的问题是,如何在不影响figcaption元素包装或缩进的情况下获取img元素左上角的p

代码示例:https://jsfiddle.net/ComputerWhiz/mp9sdqq3/1/

1 个答案:

答案 0 :(得分:8)

我相信这就是你所追求的:

img {
  width: 400px;
  clear: left;
  margin-bottom: 1px;
  margin-right: 10px;
}

figcaption {
  background-color: black;
  color: white;
  max-width: 400px;
  font-size: 10px;
  display: block;
  float: left;
  position: absolute;
  top: 0;
}

figure {
  position: relative;
  float: left;
}
<figure><img src="http://www.aviatorcameragear.com/wp-content/uploads/2012/07/placeholder.jpg">
  <figcaption>Copyright Here</figcaption>
</figure>
<figure><img src="http://www.aviatorcameragear.com/wp-content/uploads/2012/07/placeholder.jpg">
  <figcaption>Copyright Here</figcaption>
</figure>
<p>This test should be wrapped around the image and should not be affected by the figcaption.This test should be wrapped around the image and should not be affected by the figcaption.This test should be wrapped around the image and should not be affected
  by the figcaption.This test should be wrapped around the image and should not be affected by the figcaption.This test should be wrapped around the image and should not be affected by the figcaption.This test should be wrapped around the image and should
  not be affected by the figcaption.This test should be wrapped around the image and should not be affected by the figcaption.This test should be wrapped around the image and should not be affected by the figcaption.This test should be wrapped around
  the image and should not be affected by the figcaption.This test should be wrapped around the image and should not be affected by the figcaption.This test should be wrapped around the image and should not be affected by the figcaption.This test should
  be wrapped around the image and should not be affected by the figcaption.This test should be wrapped around the image and should not be affected by the figcaption.This test should be wrapped around the image and should not be affected by the figcaption.This
  test should be wrapped around the image and should not be affected by the figcaption.This test should be wrapped around the image and should not be affected by the figcaption.</p>

您应该绝对定位<figcaption>元素,然后相对定位<figure>。绝对定位的元素相对于它们最接近的位置祖先定位,这就是为什么你想要在图上的相对定位。然后,浮动数字而不是图像。