How to Place Text over an Image using CSS?

While working with images such as creating an image gallery, post thumbnails, or doing any such kind of task, we might need to place the text over the images as their caption.

Something like the below image:

Place Text Over an Image
Top Left Text
Top Right Text
This is the Centered Text
Bottom Left Text
Bottom Right Text

The easiest way of placing the text over an image in CSS is to make use of the position property. But how?

To do this, you have to first enclose the image and the text both inside a <div> element. After doing this, you have to set the position of this <div> to relative and the text position to absolute.

In case you don’t know, an absolutely positioned element is positioned relative to its nearest positioned ancestor. This is the reason, we set the position of the div to relative and that of the text to absolute so that the text could be positioned relative to this containing div.

To change the position of the text inside the div element, you can use the top, left, bottom & right properties.

Here is a fully working example:

Example:

/* Image and Text Container */
div.container{
   overflow: hidden;
   max-height: 250px;
   position: relative;
}
div.container img{
   width: 100%;
}

/* Top Left Text */
div.top-left{
    position: absolute;
    top: 10px;
    left: 10px;
}

/* Top Right Text */
div.top-right{
    position: absolute;
    top: 10px;
    right: 10px;
}

/* Center Text */
div.center{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%); 
}

/* Bottom Left Text */
div.bottom-left{
    position: absolute;
    bottom: 10px;
    left: 10px;
}

/* Bottom Right Text */
div.bottom-right{
    position: absolute;
    bottom: 10px;
    right: 10px;
}

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts