Create an Overlapping Figure Caption Using Basic CSS

I find myself needing to overlay HTML elements off and on such as a photo caption on top of a photo. The technique to accomplish is very simple and does not require anything we have not has available for years.

First create two markup elements. For my example I am using a DIV with an image inside, followed by a figcaption. You could use two DIV or other combination of elements appropriate for your situation.

<

div

class

="demo-photo"

>


<

img

src

="[path]/sad-fingers.png"

alt

="Sad Fingers"

/>


</

div

>


<

figcaption

class

="demo-photo-caption"

>


Sad Fingers

</

figcaption

>


The element you want to overlap should be the second element. This will give it a natural overlay without using a z-index. This natural overlay based on the order of the DOM tree also comes into play if you want to do single page application transitions. I guess the best way to explain it is if you could stack each element on top of another the natural order of who's on top would be the last element in the DOM tree.

So how do you get the caption to overlay the image? The trick is using position:relative and specifying an appropriate negative value for top. In this example I specified an element height of 21 pixels and a '24 pixel top position. I am not sure why I needed to move the element more than the actual height in this case, but without that is has some bottom overhang. It might be the jsFiddler styles, not sure, so your experience may vary slightly.

.demo-photo-caption


{

position

:

relative;


height

:

21px;


width

:

180px;


top

:

-24px;


color

:

#fff;


font-size

:

12pt;


background-color

: rgba(0, 0, 0, .4);

text-align

:

right;


padding

-

right

:

12px;


}?

By specifying a negative top the element is moved up, in this case 24 pixels, from its natural position. If you specify a positive number the caption would be moved down that number of pixels.

For better effect I added an opaque background (really a CSS3 property) and set the text so it would be right aligned. This is more about personal taste than anything else. You can feel free to adjust it as you need.

You can see the code and demo at http://jsfiddle.net/gTFE7/5/

Share This Article With Your Friends!

We use cookies to give you the best experience possible. By continuing, we'll assume you're cool with our cookie policy.

Install Love2Dev for quick, easy access from your homescreen or start menu.

Googles Ads Bing Pixel LinkedIn Pixel