How to Place Text Over an Image in HTML and CSS

Images are a vital part of web design and often need to be accompanied by text to provide context or convey a message.

Placing text over an image is a common technique in web design and can be accomplished using HTML and CSS.

In this tutorial, we’ll walk you through the steps to place text over an image using HTML and CSS.


HTML Code

The HTML code is the structure of your website and defines the content on your page.

To place text over an image, you will need to wrap the image in a container element, such as a div, and add the text within that container.

Here is an example of the HTML code:

<div class="container">
  <img src="image.jpg" alt="image">
  <p>This is the text over the image</p>
</div>

CSS Code

CSS, or Cascading Style Sheets, is used to style your website and add visual elements such as color, size, and positioning.

To place text over an image, you will need to use the CSS position property to position the text relative to the image.

Here is an example of the CSS code:

.container {
position: relative;
}

.container p {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
font-size: 24px;
text-align: center;
}

In the CSS code above, we have defined the container class with the position: relative property, which sets the position of the container relative to its normal position.

Then, we have defined the p element within the container class with the position: absolute property, which sets the position of the text absolute to the container.

The top: 50% and left: 50% properties center the text horizontally and vertically within the container.

The transform: translate(-50%, -50%) property moves the text up and to the left by 50% of its own height and width, which centers the text within the container.

Finally, the color, font-size, and text-align properties set the text color, size, and alignment, respectively.


Conclusion

Placing text over an image is a simple and effective way to convey a message or provide context to an image.

By combining HTML and CSS, you can easily position text over an image and add styling to make it look exactly how you want it to.

Whether you’re a beginner or an experienced web designer, you can use the steps outlined in this tutorial to place text over an image in HTML and CSS.