Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making a div "hug" its contained components [duplicate]

Tags:

html

css

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>
like image 688
Jason S Avatar asked Jun 28 '16 23:06

Jason S


People also ask

How do I make a div hug its content?

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

How do I wrap all content in a div?

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.

How do I keep my div from wrapping to the next line?

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 .


1 Answers

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

like image 142
Ricky Avatar answered Sep 18 '22 19:09

Ricky