April 25, 2012

Captions on an image with CSS

Question by StickFigs

I’m trying to make “meme”-looking captioned images with CSS using an <img> object and two <p> objects styled with CSS. Right now I have a <div> which contains the <img> and then the two <p>‘s. What I want to do is have the picture positioned in the top-left corner of the div and then I set the z-index to -1 and THEN somehow position the two p objects over the image but positioned relative to the top-left corner of the div.

This is so I can set the top: y and left: x values of the p objects such that they will be positioned accordingly relative to the top-left of the div and in turn the image.

But when I try to set position: relative for the p objects there’s a problem where the first p is correctly placed but the 2nd p is positioned relative to the first one so even though it’s at top: 0, left: 0 it’s still lower than it should be.

How can I fix this?

Answer by Kirean

check out this jsfiddle:


relevant CSS

.meme_container {
 position: relative;   
.meme_container .top_meme {
.meme_container .bottom_meme {

and the html

<div class="meme_container">
<img src="https://www.google.com/images/srpr/logo3w.png"/>
<p class="top_meme">This is a caption 1</p>
<p class="bottom_meme">This is a caption 2</p>

Answer by Starx

One way is to use Pseudo element like :after and :before


img:after {
   content: "Hello, I am the caption";

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!