[ACCEPTED]-Image caption width to same as image-caption
So the problem is that you don't know how 7 wide the img will be, and the caption for 6 the img may exceed the width of the img, in 5 which case you want to restrict the width 4 of the caption to the width of the img.
In 3 my case, I applied display:table
on the parent element, and 2 applied display:table-caption
and caption-side:bottom
on the caption element like 1 this:
<div class="image" style="display:table;">
<img src="foo.jpg" alt="" />
<div style="display:table-caption;caption-side:bottom;">This is the caption.</div>
</div>
You can apply display:table;
and an arbitrary initial 5 width, eg. width:7px;
to the parent block like figure
and 4 everything will work as expected!
Here is 3 a live demo: http://jsfiddle.net/blaker/8snwd/
This solution's limitation 2 is that IE 7 and earlier do not support 1 display:table;
and IE 8 requires your doctype to be !DOCTYPE
.
Sources:
- http://www.lifeathighroad.com/web-development/forcing-to-wraps-to-the-width-of-an-image-using-css-only/
- W3Schools (can't post link due to stackoverflow's 2-link limit for people with less than 10 rep)
If the problem is the caption being too 6 long, you can always use
div.image {
width: 200px; /* the width you want */
max-width: 200px; /* same as above */
}
div.image div {
width: 100%;
}
And the caption 5 will stay static. Also, the tag name is 4 img, not image.
Or, if you want to detect 3 your image width, you can use jQuery:
$(document).ready(function() {
var imgWidth = $('.image img').width();
$('.image div').css({width: imgWidth});
});
That 2 way, you're getting the image width, then 1 you set the caption width to it.
The only way to do captioning properly is 8 to enclose the image and caption in a table 7 constructed from span elements with table, table-row 6 and table-cell css attributes.
Any other 5 method (including HTML5 figure tags) either 4 gives width mismatches or causes unwanted 3 line breaks.
If your method must work in 2 a non-css3 browser, then a table is probably 1 the best bet.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.