How Do I Add Text Over Image With HTML CSS?

There are more than one ways of adding text over image with HTML and CSS.

Here is a quick and easy way to get image text overlay effect.

Let’s start by adding these codes in HTML and CSS file.

HTML

<div>
  <section>
    <img src="rocket.jpg" alt="rocket in space">
    <h2>Rocket In Space</h2>
  </section>
</div>

CSS

*{
    box-sizing: border-box;
    margin: 0;
    padding: 0;;
}
div{ 
    width: 350px;
    margin: 0 auto;
}

We have given the width to the div and set margin (top and bottom) to 0 and margin (left and right) to auto.

text overlay effect

This is will center the image and text.

Now let’s give image width 100% so that it will occupy the whole width of div and also style h2 text.

img{
    width: 100%;
}

h2{
    background-color: black;
    color: white;
    text-align: center;
    padding: 20px;
    width: 100%;
}
text overlay effect

Now add position: relative property to section and position: absolute property to h2.

section{
    position: relative;
}

h2{
    background-color: black;
    color: white;
    text-align: center;
    padding: 20px;
    width: 100%;
    position: absolute;
} 

Remember that position absolute property moves element in relation to its containing element.

In our example, we added position relative to section because we want to move h2 element in relation to section element.

Section is parent element of both img and h2 element.

Now add box offset property top in h2.

Let’s also add opacity property for styling purpose.

h2{
    background-color: black;
    color: white;
    text-align: center;
    padding: 20px;
    width: 100%;
    position: absolute;
    top: 40%;
    opacity: 0.7;
} 

Complete CSS code.

*{
    box-sizing: border-box;
    margin: 0;
    padding: 0;;
}

div{ 
    width: 350px;
    margin: 0 auto;
}

section{
    position: relative;
}

img{
    width: 100%;
}

h2{
    background-color: black;
    color: white;
    text-align: center;
    padding: 20px;
    width: 100%;
    position: absolute;
    top: 40%;
    opacity: 0.7;
} 

Final Output

text overlay effect