Last updated: 13th November, 2024
I was working on an online art gallery recently when I came across a requirement where I wanted to add a transparent text over an image. The text would describe the image and I could have used the title property of the image to do that. However, to read the title, one has to role the mouse over the image to read the text. Moreover, a text over image would look good.It was not as difficult as thought it would be. Using CSS I could achieve what I planned, and it is simple. I’ll share this with you.
➡️ One way to do this is by using opacity property in CSS. However, the method I used in this example is different.
Here’s what I did to get the result I wanted. I need a DIV element that will serve as a container and a <span> element that will have the text.
Follow these steps.
First, add the DIV element on your web page and assign the image as the background. Since its a container, any other element you add, will rest on top of the background image. All we need then is to position the element with text, at the bottom (or any where) of the DIV and create a transparent view of the text.
<!doctype html> <html> <head> <style> body { margin:2px; padding:0; } .myImage { font:14px Verdana; background:url('image.jpg') no-repeat; width:706px; height:209px; } </style> </head> <body> <div class="myImage"> <span>A Text over an image</span> </div> </body> </html>
It will look like this. 👇
We now have the DIV showing an image as background and a text over it. As expected, it will show the text at the top location inside the DIV. I want the text at the bottom, with transparent effect. Therefore, I’ll add some CSS properties to the <span>.
span {
display: block;
background: #000;
background: rgba(0, 0, 0, 0.6);
color: #FFF;
padding: 20px 5px;
}
I have now added a darkish, transparent background to the text.
The rgba() method takes 4 parameters. The first three Zeros will return the color black and the last parameter 0.6 is for opacity, to give the element a transparent look.
You can adjust the opacity by assigning a value between "0.1" to "0.9".
Finally, I’ll set the position of the <span> along with <div> element. I’ll set the DIV’s position as "relative" and the <span> as absolute (so I can move it anywhere I want inside the container), with its ‘bottom’, ‘left’ and ‘right’ property set as 0.
<!doctype html> <html> <head> <style> .myImage { background: url('https://www.encodedna.com/images/theme/easy-image-resizer.jpg') no-repeat; width: 350px; height: 350px; position: relative; } span { display: block; position:absolute; bottom:0; left:0; right:0; background:#000; background:rgba(0, 0, 0, 0.6); color:#FFF; padding:20px 5px; } </style> </head> <body> <div class="myImage"> <span> A Text over an image. <a href="#" style="color:#FD9C00;text-decoration:none;">See more examples.</a> </span> </div> </body> </html>