仅设置背景颜色不透明度,CSS 中不影响文本
要在 CSS 中仅设置背景颜色而不透明度,这有助于创建叠加卡片或弹出窗口。我们可以通过减小 alpha 变量的值来降低背景颜色的不透明度,同时将颜色值赋给 background-color 属性。
在这篇文章中,我们有三个带有背景颜色的 div 盒子,我们的任务是在 CSS 中仅设置背景颜色的不透明度,而不影响文本。
仅设置背景颜色不透明度的方法
以下是本文将讨论的,在 CSS 中仅设置背景颜色而不影响文本的方法列表,其中包含分步说明和完整的示例代码。
使用 rgba 设置背景不透明度
要在 CSS 中仅设置背景颜色而不影响文本的不透明度,我们将使用 CSS background 属性和 **rgba** 值,并使用 **alpha** 值调整不透明度。
- 我们使用 div 元素创建三个盒子,并设置盒子的 padding。
- 然后,我们使用 CSS **background** 属性使用 **rgba** 值设置盒子的背景颜色。
- 我们使用了三个盒子来显示不同的不透明度值,分别为 30%、70% 和原色。
示例
这是一个完整的示例代码,它实现了上述步骤,使用 **rgba** 值仅设置背景颜色而不影响文本的不透明度。
<html>
<head>
<style>
div {
background: rgb(4, 175, 47);
padding: 30px;
}
.thirty {
background: rgba(4, 175, 47, 0.3);
}
.seventy {
background: rgba(4, 175, 47, 0.7);
}
.original {
background: rgba(4, 175, 47, 1);
}
</style>
</head>
<body>
<h3>
Setting opacity only to background color
not on the text in CSS
</h3>
<p>
In this example we have used <strong>rgba
</strong> value to set the opacity only to
background color not on the text in CSS.
</p>
<div class="thirty">
Background with 30% opacity
</div>
<div class="seventy">
Background with 70% opacity
</div>
<div class="original">
Background with default opacity
</div>
</body>
</html>
使用 hsla 设置背景不透明度
在这种方法中,要在 CSS 中仅设置背景颜色而不影响文本的不透明度,我们将使用 CSS background-color 属性和 **hsla** 值,并使用 **alpha** 值调整不透明度。
- 我们使用 CSS **background-color** 属性使用 **hsla** 值设置盒子的背景颜色。
- 然后,我们使用了三个盒子来显示不同的不透明度值,分别为 30%、70% 和原色。
示例
这是一个完整的示例代码,它实现了上述步骤,使用 **hsla** 值仅设置背景颜色而不影响文本的不透明度。
<html>
<head>
<style>
div {
padding: 30px;
}
.thirty {
background-color: hsla(135, 96%, 35%, 0.3);
}
.seventy {
background-color: hsla(135, 96%, 35%, 0.7);
}
.original {
background-color: hsla(135, 96%, 35%, 1);
}
</style>
</head>
<body>
<h3>
Setting opacity only to background color
not on the text in CSS
</h3>
<p>
In this example we have used <strong>hsla
</strong> value to set the opacity only to
background color not on the text in CSS.
</p>
<div class="thirty">
Background with 30% opacity
</div>
<div class="seventy">
Background with 70% opacity
</div>
<div class="original">
Background with default opacity
</div>
</body>
</html>
结论
在本文中,为了在 CSS 中仅设置背景颜色而不影响文本的不透明度,用户可以使用 **rgba** 或 **hsla** 值降低颜色的不透明度。如果用户使用图像或其他任何内容作为背景,他们可以为背景和内容创建一个单独的 div,并降低背景 div 的不透明度。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP