10

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>
Jason S
  • 184,598
  • 164
  • 608
  • 970

4 Answers4

8

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

Ricky Ruiz
  • 25,455
  • 6
  • 44
  • 53
2

Since divs are block elements by default, all you need to do is add display: inline-block; to div.figure. Like so:

div.figure { 
  border: 1px solid black;
  display: inline-block;
}
<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>
imtheman
  • 4,713
  • 1
  • 30
  • 30
1
.figure {
  border: 1px solid #000;
  width: auto;
  display: inline-block;
}

Its pretty self explanatory though, Width auto states.. its automatic. The inline block is doing the work though. It tells it to only be the width of its children. so more can fit "inline" with it.

Michael Mano
  • 3,339
  • 2
  • 14
  • 35
  • what's the default width, if you don't put `width: auto` ? – Jason S Jun 28 '16 at 23:21
  • For inline-block elements the default width is auto so you don't need to specify it, divs will be placed next to each other until they no longer fit horizontally and will break into another line. For block level elements width is 100% by default, divs will be placed vertically after each other. – Ricky Ruiz Jun 28 '16 at 23:47
0

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).

Mitchel Jager
  • 435
  • 4
  • 18