乐闻世界logo
搜索文章和话题

How to set css opacity only to background color not the text on it

3个答案

1
2
3

To achieve a transparent background with opaque text, use the rgba color value in CSS to set the background color. The rgba function takes four parameters: red, green, blue, and alpha (transparency), where alpha ranges from 0 (fully transparent) to 1 (fully opaque).

Here is a simple example:

css
.transparent-background { /* Set text color to opaque black */ color: #000000; /* Set background color to semi-transparent white */ background-color: rgba(255, 255, 255, 0.5); }

In the CSS class above, the text color is specified using a hexadecimal value, ensuring opaque text. The background color uses rgba with alpha set to 0.5, meaning the background is semi-transparent. This achieves a semi-transparent background while keeping the text content opaque.

HTML elements using this class are as follows:

html
<div class="transparent-background"> This text has a semi-transparent background, but the text itself is opaque. </div>

Using this approach, the text remains opaque regardless of the background color chosen.

2024年6月29日 12:07 回复

My trick is to create a transparent PNG and use background: url().

2024年6月29日 12:07 回复

The simplest approach is to use two div elements: one with a background and one with text.

shell
#container { position: relative; width: 300px; height: 200px; } #block { background: #CCC; filter: alpha(opacity=60); /* IE */ -moz-opacity: 0.6; /* Mozilla */ opacity: 0.6; /* CSS3 */ position: absolute; top: 0; left: 0; height: 100%; width: 100%; } #text { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } <div id="container"> <div id="block"></div> <div id="text">Test</div> </div>

Run the code snippet to view the result.

2024年6月29日 12:07 回复

你的答案