Text over image with CSS

Here two easy techniques to display text over image.
When we overlay some text over an image, the image should be dark and the text has to be white.
But if the image is not dark enough, we can add a dark gradient over the image. This makes the text more readable, with a better contrast.
There are a number of valid solutions using CSS.

Text over image, WordPress Blog example

Here a simple and flexible solution to overlay text caption over an image on a WordPress blog.
In this example we’ll use the HTML markup used by WordPress to display images with caption.
We create a layer with pseudo element :after and set a linear gradient background with a rgba value.

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;
}

Text over image, on hover

Sometimes you only want text to appear when the mouse is over the image or the image has focus.
In the example below you can see this in action: on hover we display the caption text with a dark background and a CSS transition of opacity.

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;
}