How to position text over an image with CSS?

Spread the love

Sometimes, we want to position text over an image with CSS.

In this article, we’ll look at how to position text over an image with CSS.

How to position text over an image with CSS?

To position text over an image with CSS, we use absolute positioning.

For instance, we write

<div id="container">
  <img id="image" src="https://picsum.photos/200/300" />
  <p id="text">Hello World!</p>
</div>

to add a div with the image and text.

Then we write

#container {
  height: 400px;
  width: 400px;
  position: relative;
}
#image {
  position: absolute;
  left: 0;
  top: 0;
}
#text {
  z-index: 100;
  position: absolute;
  color: white;
  font-size: 24px;
  font-weight: bold;
  left: 150px;
  top: 350px;
}

to make the text have absolute position with position: absolute;.

Then we set the left and top properties to move the text to the location we want over the image.

We set the z-index to put the text over the image.

Conclusion

To position text over an image with CSS, we use absolute positioning.

Leave a Reply

Your email address will not be published.