How to add text block over an image using CSS code?

By informerfrk

Today I am going to show you how to add text block over an image using CSS code. Suppose you have an image in your HTML page and now you want to add a text over the image. For example here is the HTML code:

<div class="textonimage">

      <img src="images/city-sunlight.jpg" />
      
      <h2><span>Text over image<br/>With transparent black background</span></h2>

</div>

Here is how it looks now:

If you open it with any browser then you will see that the text is under the image. Now you want to place the text over the image.

You can do it easily with some easy CSS code. CSS code will let you place the text over the image. Now I am going to write the CSS code for you that will do that.

CSS code to place the text over the image

There is a CSS property available which will help you to place a text over an image. This is called CSS position property. The position property of CSS specifies the type of positioning method used for an element (static, relative, absolute or fixed). This is from CSS2 version.

Use an image as a background image of the wrapping div is easy, but in this tutorial I have used the image as content, and thus belongs in the HTML. Here I am using that wrapping div as a container for absolute positioning.

Now here is the CSS code which will place the text over your image:

.textonimage { 
   position: relative; 
   width: 100%;
}

h2 { 
   position: absolute; 
   top: 155px; 
   left: 0; 
   width: 100%; 
}

Now after adding the above CSS it will looks like below picture:

This is going to put our text right up on top of the image nicely. Now it will look more better if you add transparent black background for the text. To do that, we can’t use the h2, because it is a block level element and we need an inline element without an specific width.

Let’s change the h2 element like given below:

<h2><span>Text over image<br/>With transparent black background</span></h2>

Now here is the CSS code for span:

h2 span { 
   font-weight: 700;
   color: white; 
   padding: 4px; 
   background: #000;
   opacity: 0.7;
}

Now you can see nice black transparent background for the text that is over the image.

That’s all you need to place your text block over an image. Finally it looks like the below screenshot image which looks nice:

try it yourself, run it on your browser and see the magic of CSS.

 

Leave a Reply

Your email address will not be published. Required fields are marked *