If I have HTML that looks like this:
<div class="figure">
<img src="some_image.png" />
<div><span class="caption">Fig. 1: Some caption</span></div>
</div>
Is there a way to use CSS so that the div
with class figure
has a width that is only large enough to contain the image and caption? I want to put a rectangular border around both, but I don't want to have to guess the div's width in pixels.
example below (div.figure
has a width that seems to expand to fill its available width)
div.figure {
border: 1px solid black;
}
<div class="figure">
<img src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo-med.png?v=6f86a5fa447f" />
<div><span class="caption">Fig. 1: Some caption</span></div>
</div>
Another simple way to do this is to simply add float: left , which floats the div next of elements near it. A float also makes it so a div is only as wide as it's content (Unless otherwise specified).
If you've faced the situation when you need to wrap words in a <div>, you can use the white-space property with the "pre-wrap" value to preserve whitespace by the browser and wrap the text when necessary and on line breaks. Also, you'll need the word-wrap property.
If you want to prevent them from wrapping, either remove the white space you have used for formatting, or add white-space:nowrap; to the rule for .
SOLUTION:
A <div>
is a block-level element (Same as HTML5 figure tag). So you need to specify you want an inline-block behavior adding the css property display: inline-block;
to your figure.
CODE SNIPPET:
figure {
border: 1px inset tomato;
display: inline-block;
}
<figure>
<img src="http://placehold.it/300x300" alt="my-photo"/>
<figcaption>
Fig. 1: Some caption
</figcaption>
</figure>
FURTHER READING:
How well do you know CSS display? by Chen Hui Jing - June 18, 2016
Display by Sara Cope - March 16, 2015
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With