EN
CSS - give text or image transparent background
1 answers
0 points
Is it possible to set the background of an element to partly transparent but have the content (text & images) of the element fully visible?
I was trying opacity: 50%
but I don't want the text to be affected by it:
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
.transparent {
7
background: red;
8
opacity: 50%;
9
}
10
11
</style>
12
</head>
13
<body>
14
<p class="transparent">
15
<span>Some text here...</span>
16
</p>
17
</body>
18
</html>
1 answer
0 points
You can use rgba colors, which works like rgb but the fourth parameter a
(alpha) is a number between 0
and 1
(or a percentage value) that sets the opacity. The number 1
corresponds to 100% (full opacity) and 0
makes the element invisible.
Quick solution:
xxxxxxxxxx
1
background-color: rgba(255, 0, 0, 0.5); /* sets element color to red with opacity: 50% */
Practical example
1. Using HTML style
attribute
xxxxxxxxxx
1
2
<html>
3
<body>
4
<p style="background-color: rgba(255, 0, 0, 0.5);">
5
<span>Some text here...</span>
6
</p>
7
</body>
8
</html>
2. Using CSS
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
.transparent-background {
7
background: rgba(255, 0, 0, 0.5);
8
}
9
10
</style>
11
</head>
12
<body>
13
<p class="transparent-background">
14
<span>Some text here...</span>
15
</p>
16
</body>
17
</html>
Working with images
Analogically, when you are working with images, you need to set the image container background to rgba color with some opacity.
1. Using HTML style
attribute
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div style="background-color: rgba(255, 0, 0, 0.5);">
5
<img src="https://dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png" width="100px" />
6
</div>
7
</body>
8
</html>
2. Using CSS
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
.transparent-background {
7
background: rgba(255, 0, 0, 0.5);
8
}
9
10
</style>
11
</head>
12
<body>
13
<div class="transparent-background">
14
<img src="https://dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png" width="100px" />
15
</div>
16
</body>
17
</html>
References
0 commentsShow commentsAdd comment