Signup/Sign In
LAST UPDATED: AUGUST 5, 2021

How to position text over an image using CSS?

Sometimes text can be added to the images on the webpage. The text on images can be used as captions to describe images. The text cannot be positioned over an image using only HTML elements. For this, we need to use CSS properties.

In this tutorial, we will be learning to position text over images using CSS.

Using CSS position property

The CSS position property can be used to position text on the image. To do so add position:relative to the image and position:absolute to the text.

Add both elements within an <div> element. We can also add top, bottom, left, or right properties to position text on the image to a specific place.

Example: Position text over an image using CSS

Here in this program, we have simply positioned the text over the image.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
<style>
	.container {
	  position: relative;
	}
	.text {
	 position: absolute;
	 color: white;
	 top: 5px;	 
	}
</style>
</head>
<body>
    <h2> Positioning the text over image</h2>
	<div class="container">
	 <img src="https://s3.ap-south-1.amazonaws.com/s3.studytonight.com/user/profile/picture/iamabhishek1622449489_profile.png" alt="image">
	 <h4 class="text"> Add caption to the image </h4>
	</div>
</body>
</html>

Output

Here is the output of the above program.

text over image

Example: Add the text over the image at a specific position

We can position the text anywhere on the image. Here in this program, we will add multiple texts to illustrate text positioning on images.

Conclusion

In this tutorial, we have learned to position the text over the image using CSS. The text and images are position absolute and relative respectively. Further, we can add top, bottom, left, right properties to position it on a specific region on the image.



About the author: