OneBite.Dev - Coding blog in a bite size

overlay text on an image css

Code snippet for how to overlay text on an image css with sample and detail explanation

Overlaying text on an image can be a great way to enhance your website layouts and keep users engaged. In this article, we are going to explore and guide you thru the method of how you can accomplish this task using CSS.

Code Snippet for Overlay Text on an Image

The following is a simple CSS code snippet to overlay text on an image:

.image-container {
  position: relative;
}

.text-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  color: white;
  padding: 20px;
  text-align: center;
  background: rgba(0,0,0,0.5);
}

And in your HTML:

<div class="image-container">
  <img src="your-image.jpg" alt="" />
  <div class="text-overlay">Your text Here</div>
</div>

Code Explanation for Overlay Text on an Image

Firstly, the .image-container class is given a position:relative. This is because positioning in CSS works in contexts. When you position something absolute, it will position itself relative to the nearest positioned parent it has. In this case, .text-overlay is positioning itself according to .image-container.

The .text-overlay class is given a position:absolute which means it will be positioned in relation to the .image-container, in this case starting from the top left corner (given by top:0 and left:0). width:100% and height:100% make sure it stretches across the whole container, covering the entire image.

The color:white property changes the color of your text, while the padding:20px gives some space around your text, so it doesn’t stick to the sides of the image-container.

text-align:center aligns your text to the center, both horizontally and vertically.

Lastly, background: rgba(0,0,0,0.5) adds an semi-transparent black overlay to the image to make the text more readable.

With this method, you can have an effective text overlay on your image that would improve your design and highlight the necessary texts.

css