How to Position Text Over an Image using CSS.

Text over images is common in websites for example when creating image cards or photo galleries where you may need to add some caption text or description over the image. In such situations, you can use the CSS position properties to place the text over an image.

The trick is to place both the image and text in the same container <div> element and then give this container a position: relative property and the text position:absolute.

Then use the top, bottom, left, and right properties to set the position of text from the container’s edges.

The example below demonstrates how this can be achieved.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
h1{
   text-align: center;
}
.container {
   width: 80%;
   margin: 10% auto;
   position: relative;
   text-align: center;
}
img{
   width: 100%;
   height: 60vh;
}
.text{
   font-size: 25px;
   color: #080808;
   font-weight: bolder;
   text-transform: uppercase;
}
.bottom-left, .top-left,.top-right,.bottom-right,.center {
   position: absolute;
}
.bottom-left{
   bottom: 8px;
   left: 16px;
}
.top-left{
   top: 8px;
   left: 16px;
}
.top-right{
   top: 8px;
   right: 16px;
}
.bottom-right {
   bottom: 8px;
   right: 16px;
}
.center {
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
}
</style>
</head>
<body>

<div class="container">
<!--img src="images/background.jpg"-->
<img src="https://images.pexels.com/photos/220182/pexels-photo-220182.jpeg">
<div class="text bottom-left">Bottom Left Text</div>
<div class="text top-left" >Top Left Text</div>
<div class="text top-right">Top Right Text</div>
<div class="text bottom-right">Bottom Right Text</div>
<div class="text center">Centered Text</div>
</div>
</body>
</html>

The above code will give the output below in a web browse.

position text over image using css

Depending on the image you have used, the text may sometimes be hard to read and in such cases you need to apply gradient overlays, tinted background image, text-shadow, and other tactics to make the text appear better.