如何使用 CSS 创建具有透明背景文本的图像?


我们可以轻松创建带有透明背景文本的图像。使用 CSS 背景属性设置不透明度为 0.5 的黑色背景。使用 position 属性对齐它,并将其放置在图像的底部。在那里放置文本,即图像上的透明背景文本。让我们看看如何使用 HTML 和 CSS 创建带有透明背景文本的图像。

设置图像容器

设置图像容器,在其内显示图像和一些内容。此内容进入底部 −

<div class="imageContainer">
   <img src="https://tutorialspoint.com/static/images/home/hero-banner.png">
   <div class="imageContent">
      <h1>A Man</h1>
      <h3>A man sitting on a chair with a laptop.</h3>
   </div>
</div>

对齐图像容器

为设置图像容器,使用具有值 relative 的 position 属性 −

.imageContainer {
   display: inline-block;
   position: relative;
}

对齐图像上的内容

使用具有值 absolute 的 position 属性对齐图像上的内容。内容在图像底部;因此,将 bottom 属性设置为值 0 −

.imageContent {
   position: absolute;
   bottom: 0;
   background: rgba(29, 6, 43, 0.5);
   color: #f1f1f1;
   width: 100%;
   padding: 20px;
}

示例

以下是如何使用 CSS 创建带有透明背景文本的图像的代码 −

<!DOCTYPE html>
<html>
<head>
   <style>
      * {
         box-sizing: border-box;
      }
      body {
         font-family: Arial;
         font-size: 17px;
      }
      .imageContainer {
         display: inline-block;
         position: relative;
      }
      .imageContent {
         position: absolute;
         bottom: 0;
         background: rgba(29, 6, 43, 0.5);
         color: #f1f1f1;
         width: 100%;
         padding: 20px;
      }
   </style>
</head>
<body>
   <h2>Image with Transparent Text</h2>
   <div class="imageContainer">
      <img src="https://tutorialspoint.com/static/images/home/hero-banner.png">
      <div class="imageContent">
         <h1>A Man</h1>
         <h3>A man sitting on a chair with a laptop.</h3>
      </div>
   </div>
</body>
</html>

更新于:14-12-2023

530 次浏览

职业生涯起航

完成课程获取认证

开始
广告
© . All rights reserved.