PHP前端开发

仅将不透明度设置为背景颜色,而不是 CSS 中文本的不透明度

百变鹏仔 4周前 (09-19) #CSS
文章标签 明度

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

我们可以通过减小 alpha 变量的值来降低背景颜色的不透明度,同时将颜色值分配给“背景颜色”属性。

语法

用户可以按照以下语法仅将不透明度设置为背景色,而不是 CSS 中的文本。

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

用户可以使用‘rgba’或‘hsla’设置背景颜色;这里“a”代表 alpha 不透明度,其值介于 0 和 1 之间。

立即学习“前端免费学习笔记(深入)”;

示例 1

在下面的示例中,我们创建了 HTML div 元素并使用“background”属性设置背景颜色。我们使用“rgba”值来设置背景颜色。我们将“红色”颜色设置为背景,不透明度为“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

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

用户可以在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 元素的 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 的不透明度。