在 CSS 中仅设置背景颜色的不透明度,而不影响文本的不透明度

cssweb developmentfront end technology更新于 2024/3/22 2:52:17

在 CSS 中,我们可以使用 CSS 的"background"属性为特定的 HTML 元素设置背景。有时,我们可能需要降低背景颜色的不透明度,而不影响 HTML 元素的内容。

我们可以通过降低 alpha 变量的值,同时将颜色值赋给"background color"属性来降低背景颜色的不透明度。

语法

用户可以按照以下语法在 CSS 中仅设置背景颜色的不透明度,而不影响文本的不透明度。

background: rgba(255, 0, 0, opacity);
或
background-color: hsla(0, 100%, 30%, opacity);

用户可以使用"rgba"或"hsla"设置背景颜色;此处"a"表示 Alpha 透明度,取值范围为 0 到 1。

示例 1

在下面的示例中,我们创建了 HTML div 元素,并使用"background"属性设置了背景颜色。我们使用"rgba"值来设置背景颜色。我们将"red"颜色设置为背景,不透明度为"0.1",用户可以在输出中观察到。

<html>
<head>
   <style>
      .div {
         background: rgba(255, 0, 0, 0.1);
         height: 100px;
         width: 500px;
      }
   </style>
</head>
<body>
   <h3>Setting up the background opacity without affecting the content of the div element</h3>
   <div class = "div">
      Hello! How are you?
   </div>
</body>
</html>

示例 2

在下面的示例中,我们使用 CSS 属性"background-color"设置 HTML div 元素的背景。此外,我们使用"hsla"值作为背景,并将 alpha 不透明度设置为"0.2"。

用户可以在 0 到 1 之间增加或减少不透明度值,并观察背景颜色的变化。

<html>
<head>
   <style>
      .div {
         background-color: hsla(0, 100%, 30%, 0.2);
         height: 100px;
         width: 500px;
      }
   </style>
</head>
<body>
   <h3>Setting up the background opacity using the background-color: hsla CSS property without affecting the content of the div element </h3>
   <div class = "div">
      This is a content of the div element.
   </div>
</body>
</html>

示例 3

我们可以将背景 div 与内容 div 分开,并将 div 元素的背景颜色设置为较低的不透明度。

这里,我们有一个父 div。在父 div 中,我们有背景 div 和内容 div。背景 div 和内容 div 的尺寸与父 div 相同。我们可以为这两个 div 元素设置 z-index 属性,使内容 div 显示在背景 div 上方。

之后,我们可以使用 CSS 的"opacity"属性仅降低背景 div 的不透明度。这样,我们可以将背景 div 放在内容 div 下方,并调整背景 div 的不透明度。

<html>
<head>
   <style>
      #parent {
         width: 500px;
         height: 150px;
         position: relative;
      }
      #content {
         position: absolute;
         width: 100%;
         height: 100%;
         color: white;
         font-size: 1.2rem;
         top: 0;
         left: 0;
      }
      #background {
         background: blue;
         filter: alpha(opacity=30);
         position: absolute;
         height: 100%;
         width: 100%;
         top: 0;
         left: 0;
      }
   </style>
</head>
<body>
   <h3>Setting up the background opacity using the filter: alpha(opacity = value) CSS property without affecting the content of the div element </h3>
   <div id = "parent">
      <div id = "background"></div>
      <div id = "content"> This is the content of the div element.</div>
   </div>
</body>
</html>

用户学习了如何在不影响文本或 div 内容透明度的情况下设置背景颜色的不透明度。用户可以在使用"rgba"或"hsla"值时降低颜色的不透明度。如果用户使用图像或其他任何内容作为背景,他们可以为背景和内容创建一个单独的 div,并降低背景 div 的不透明度。


相关文章


有用资源