In this article, we’ll see how to place text over an image using HTML and CSS.
The image should be dark enough and the text has to be white, to make the text easier to read and meet accessibility standards.
But if the image is not dark enough, we can add a dark gradient over the image. This makes the text more readable, with better contrast.
There are a number of valid solutions and techniques using CSS.
Text over an image: WordPress example
A simple and flexible solution to overlay text caption over an image on a WordPress site.
In this example, we’ll use the HTML markup used by WordPress to display images with captions.
We create a layer with the pseudo-element :after and set a linear gradient background with a rgba value.
Original
Linear gradient
HTML
<figure class="wp-caption">
<img class="demo" src="image.jpg" alt="Image" />
<figcaption class="wp-caption-text">This is a caption text</figcaption>
</figure>
CSS
.wp-caption {
position: relative;
padding: 0;
margin: 0;
}
.wp-caption img {
display: block;
max-width: 100%;
height: auto;
}
.wp-caption:after {
content: "";
position: absolute;
display: block;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0) linear-gradient(to bottom, rgba(0, 0, 0, 0) 0px, rgba(0, 0, 0, 0.6) 100%) repeat 0 0;
z-index: 1;
}
.wp-caption-text {
display: block;
position: absolute;
width: 100%;
color: #fff;
left: 0;
bottom: 0;
padding: 1em;
font-weight: 700;
z-index: 2;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
To add your custom CSS to your WordPress theme please navigate to Appearance » Customize page in your WordPress admin, click on the Additional CSS tab from the left panel and add the code below.
Text over an image: on mouse over
Sometimes you only want the text to appear when you mouse over the image, or when the image has an active or focused state.
In the example below, we display on mouse hover the caption text with a dark background and a CSS opacity transition.
HTML
<figure class="wp-caption">
<img class="demo" src="image.jpg" alt="Image" />
<figcaption class="wp-caption-text">This is a caption text</figcaption>
</figure>
CSS
.wp-caption {
position: relative;
padding: 0;
margin: 0;
}
.wp-caption img {
display: block;
max-width: 100%;
height: auto;
}
.wp-caption-text {
opacity: 0;
position: absolute;
width: 100%;
color: #fff;
left: 0;
bottom: 0;
padding: 0.75em 1em;
font-weight: 700;
z-index: 2;
-webkit-box-sizing: border-box;
box-sizing: border-box;
background-color: rgba(0,0,0,.7);
-webkit-transition: opacity .3s ease-in-out;
transition: opacity .3s ease-in-out;
}
.wp-caption:hover .wp-caption-text {
opacity: 1;
}
High-quality WordPress Themes to build your website
Building your blog, magazine, or shop is now easy with our Premium WordPress themes. We craft beautiful and easy-to-use WordPress themes with performance, usability and SEO in mind.
Otherwise, you can try our Free WordPress themes available from the official WordPress.org repository.