Reputation: 14398
I have a relatively positioned figure
with an image in like so:
<figure>
<img src="image.jpg" width="100%" />
</figure>
figure {
position: relative;
display: block; }
figure
takes it's height from the image. Now, say I add absolutely positioned content to figure
that will sit on top of the image. The content has no set height and could be multi-line. I would usually do this sort of thing like this:
<figure>
<img src="image.jpg" width="100%" />
<figcaption>
<span>Lorem ipsum dolor sit amet, consectetur adipiscing elit</span>
</figcaption>
</figure>
figure {
position: relative;
display: block; }
figcaption {
position: absolute;
display: table;
top:0; right:0;
bottom:0; left:0;
width:100%; height:100%; }
figcaption span {
display: table-cell;
vertical-align: middle; }
However, despite figcaption
having 100% height and width, plus all 4 positionings set to 0, it still doesn't fill the whole figure, meaning the vertical centering doesn't work.
Is there a way to make figcaption
take 100% height when figure
takes it's height from the image within? Or is there another way to vertically center in this situation?
Upvotes: 0
Views: 141
Reputation: 9923
You just have to set margin: auto;
on figcaption
, you was pretty close.
figure {
position: relative;
display: block;
}
figcaption {
position: absolute;
display: table;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto; /* Added */
width: 100%;
height: 100%;
}
figcaption span {
display: table-cell;
vertical-align: middle;
}
<figure>
<img src="image.jpg" width="100%" />
<figcaption> <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit</span>
</figcaption>
</figure>
Upvotes: 1
Reputation: 10786
Setting the top and bottom to 0 doesn't automatically center it. Here's an example: http://jsfiddle.net/sgcdpert/
figcaption {
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translateX(-50%) translateY(-50%);
-moz-transform: translateX(-50%) translateY(-50%);
-o-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
}
Upvotes: 1