How to Position Text Over an Image With CSS

Jay Singh Feb 02, 2024
How to Position Text Over an Image With CSS

Texts can be added to photos on a webpage in some cases, and image captions can be created from the text on the image. The text cannot be placed over an image using HTML components solely.

CSS attributes will be required for this. This tutorial will show how to position text over an image with CSS.

Position Text Over an Image With CSS

Text on the picture can be positioned using the CSS position attribute. To do so, provide the picture position:relative and the text position:absolute.

Within a <div> element, add both components. We may use the top, bottom, left, and right properties to position text on the picture at a certain location.

Code:

<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.container {
  position: relative;
  text-align: center;
  color: blue;
}
.bottom-left {
  position: absolute;
  bottom: 5px;
  left: 12px;
}
.top-left {
  position: absolute;
  top: 5px;
  left: 12px;
}
.top-right {
  position: absolute;
  top: 5px;
  right: 12px;
}
.bottom-right {
  position: absolute;
  bottom: 5px;
  right: 12px;
}
.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
</head>
<body>

<h2>Image Text</h2>
<p>How to place text over an image:</p>

<div class="container">
  <img src="/img/DelftStack/logo.png" alt="DelftStack Logo" style="width:100%;">
  <div class="bottom-left">Left Bottom</div>
  <div class="top-left">Left Top</div>
  <div class="top-right">Right Top</div>
  <div class="bottom-right">Right Bottom</div>
  <div class="centered">Center</div>
</div>
</body>
</html>

Here’s another example of positioning the text over an image with CSS.

Code:

<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="/img/DelftStack/logo.png" alt="DelftStack Logo">
     <h4 class="text"> Add any text to the image </h4>
    </div>
</body>
</html>

Related Article - CSS Alignment