opacity (part 2)

opacity (part 2)

ยท

2 min read

This blog is in continuation of the first blog on opacity where we learnt to set opacity to various degrees on an element (you can read it here).

Although we can write text over the element having the opacity property, the element's opacity property will also get applied to the text (which we don't want in general). So, we'll understand as how to avoid this situation.

Now, let's understand as how to write text over the elements having the opacity property with the same example:

1.PNG

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #red{
            background-color: red;
            height: 10rem;
            width: 10rem;
            border-radius: 5rem;
            top: 0rem;
            position: absolute;
        }
        #green{
            background-color: green;
            height: 10rem;
            width: 10rem;
            border-radius: 5rem;
            position: absolute;
            top: 0rem;
            left: 7rem;
        }
        #violet{
            background-color: blueviolet;
            height: 10rem;
            width: 10rem;
            border-radius: 5rem;
            position: absolute;
            top: 6rem;
            left: 3rem;
        }
    </style>
</head>

<body>
    <div id="red"></div>
    <div id="green"></div>
    <div id="violet"></div>
</body>
</html>

Now, let's decrease the opacity of the violet circle and see what happens:

#violet{
            background-color: blueviolet;
            height: 10rem;
            width: 10rem;
            border-radius: 5rem;
            position: absolute;
            top: 6rem;
            left: 3rem;
            display: flex;
            justify-content: center;
            align-items: center;
            opacity: 0.2;
        }

2.PNG

Can you see the text in the violet circle (I can see only very faint text).

Here's the solution as per MDN: To change the opacity of the background only, use the background property with a color value that allows for an alpha channel.

so what does โ˜๏ธ this means? This means that we have to give background-color property in form of "rgba" where a stands for alpha and defines opacity (you can easily find rgb for any color on google).

Let's do this for the violet circle (and remove the opacity property).

background: rgba(138, 43, 226, 0.2)

3.PNG

In the above pic, we could see that the text is visible even if the opacity of the background circle in 0.2.

So, that is all about opacity.

I hope the above article added some value.

I write articles related to web development. Follow me here if you are learning the same.

Have an awesome day ahead ๐Ÿ˜€!

my twitter handle: @therajatg

If you are the linkedin type, let's connect: linkedin.com/in/therajatg

ย