📜  在图像上方添加黑色 css (1)

📅  最后修改于: 2023-12-03 14:51:25.482000             🧑  作者: Mango

在图像上方添加黑色 CSS

有时候我们需要在图像上方添加一些文本或者其他元素,比如图片标题、水印等。这时候我们可以使用 CSS 通过绝对定位在图像上方添加元素。

使用方法

在 HTML 中添加图片,可以使用以下代码:

<img src="image.jpg" alt="Image">

然后在 CSS 中添加以下代码:

img {
  position: relative;
  display: block; /* 使图片以块级元素显示 */
}

img:before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.5); /* 黑色半透明背景 */
  z-index: 1; /* 将黑色背景置于图片之上 */
}

这样,就可以在图像上方添加一个黑色半透明背景。如果需要添加文本等其他元素,只需要在 img:before 伪元素中添加对应的样式即可。

代码片段

以下是完整的代码片段:

<style>
  img {
    position: relative;
    display: block; /* 使图片以块级元素显示 */
  }

  img:before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5); /* 黑色半透明背景 */
    z-index: 1; /* 将黑色背景置于图片之上 */
  }

  /* 添加图片标题 */
  img:after {
    content: attr(alt);
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    background-color: rgba(0,0,0,0.5);
    color: #fff;
    padding: 10px;
    box-sizing: border-box;
    font-size: 0.8em;
    font-weight: bold;
    z-index: 2;
  }
</style>

<img src="image.jpg" alt="Image">

注意将 HTML 和 CSS 分别写在对应的文件中或者放置在对应的标签中。

以上代码片段可以在任意 HTML 文件中使用,只需要替换 src 属性的值和 alt 属性的值即可。更多用法可以自行实践。