在 CSS 中,我們可以使用 CSS 的“background”屬性設(shè)置特定 HTML 元素的背景。有時(shí),我們可能需要降低背景顏色的不透明度而不影響 HTML 元素的內(nèi)容。
我們可以通過減小 alpha 變量的值來降低背景顏色的不透明度,同時(shí)將顏色值分配給“背景顏色”屬性。
語(yǔ)法
用戶可以按照以下語(yǔ)法僅將不透明度設(shè)置為背景色,而不是 CSS 中的文本。
background: rgba(255, 0, 0, opacity); or background-color: hsla(0, 100%, 30%, opacity);
登錄后復(fù)制
用戶可以使用‘rgba’或‘hsla’設(shè)置背景顏色;這里“a”代表 alpha 不透明度,其值介于 0 和 1 之間。
示例 1
在下面的示例中,我們創(chuàng)建了 HTML div 元素并使用“background”屬性設(shè)置背景顏色。我們使用“rgba”值來設(shè)置背景顏色。我們將“紅色”顏色設(shè)置為背景,不透明度為“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>
登錄后復(fù)制
示例 2
在下面的示例中,我們使用“background-color”CSS 屬性來設(shè)置 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>
登錄后復(fù)制
示例 3
我們可以將背景div與內(nèi)容div分開,并為div元素設(shè)置不透明度較低的背景顏色。
在這里,我們有一個(gè)父 div。在父 div 中,我們有背景和內(nèi)容 div。背景和內(nèi)容 div 尺寸與父 div 相同。我們可以設(shè)置兩個(gè) div 元素的 z-index 屬性,以將內(nèi)容 div 顯示在背景 div 上方。
之后,我們可以使用 CSS 的“opacity”屬性僅降低背景 div 的不透明度。這樣,我們就可以將背景 div 放在內(nèi)容 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>
登錄后復(fù)制
用戶學(xué)會(huì)了在不影響文本或 div 內(nèi)容的不透明度的情況下設(shè)置背景顏色的不透明度。用戶可以在使用“rgba”或“hsla”值時(shí)降低顏色的不透明度。如果用戶有圖像或其他任何內(nèi)容作為背景,他們可以為背景和內(nèi)容創(chuàng)建單獨(dú)的 div,并降低背景 div 的不透明度。
以上就是僅將不透明度設(shè)置為背景顏色,而不是 CSS 中文本的不透明度的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注www.92cms.cn其它相關(guān)文章!






