How to position text over an image in a grid

3.4k Views Asked by At

I'm struggling with creating a simple grid of images with text overlaid on top. The images are a semantic part of the document and so can't be background images.

Now from looking around online It looks like the way to do this is something like this:

HTML

<article>
   <img class="image" src="image.png"/>
   <p class="text">Text to overlay</p>
</article>
<article>
   <img class="image" src="image.png"/>
   <p class="text">Text to overlay</p>
</article>
<article>
   <img class="image" src="image.png"/>
   <p class="text">Text to overlay</p>
</article>

CSS

article {
width: 33.333%;
position: relative;
float: left;
}

.image {
position: absolute;
top: 0;
left: 0;
}

.text {
z-index: 100;
position: absolute;
color: white;
font-size: 24px;
font-weight: bold;
left: 0;
bottom: 0;
}

Here the text doesn't show, and all the images end up on top of each other rather than in a grid.

When I use relative positioning then it works but then it's impossible to position the text at the base of the image. When the browser is resized the text moves around.

I've taken a good look at the following theme, and they seem to manage it using absolute positioning so I'm not sure where I'm getting it all wrong. https://cubicdemo.wordpress.com/

1

There are 1 best solutions below

0
On BEST ANSWER

Remove the positioning from the image.

I'm not sure what effect you are after precisely by I'd image it's something like this:

article {
  width: 33.333%;
  position: relative;
  float: left;
  text-align: center;
}
.image {
  display: block;
  width: 100%;
  height: auto;
  margin: auto;
}
.text {
  z-index: 100;
  position: absolute;
  color: white;
  font-size: 24px;
  font-weight: bold;
  left: 0;
  right: 0;
  bottom: 0;
}
<article>
  <img class="image" src="http://lorempixel.com/output/city-q-c-150-150-1.jpg" />
  <p class="text">Text to overlay</p>
</article>
<article>
  <img class="image" src="http://lorempixel.com/output/city-q-c-150-150-1.jpg" />
  <p class="text">Text to overlay</p>
</article>
<article>
  <img class="image" src="http://lorempixel.com/output/city-q-c-150-150-1.jpg" />
  <p class="text">Text to overlay</p>
</article>