2

To display figures, I use

<figure>
  <img …>
  <figcaption>This is a longer caption that may wrap lines.</figcaption>
</figure>

Now I'm trying to get the following via CSS:

  1. figure is horizontally centered on the page.
  2. figcaption has the same width as img. This is important for line wraps.
  3. The width comes from img.
  4. figcaption is left-aligned with img.

In other words, what I want is this (boxes for clarity):

figure layout I want

I have hacked the above mockup by giving figure an explicit width (i.e., violating 3 above), but of course that's not very desirable.

How do I get this to work? Should I look into layout: flex?

srs
  • 558
  • 4
  • 9

1 Answers1

0

min-content + flex or grid might help, display;table works too to shrink figure to the widest element.

snippet to play with below

body {/* if the matter is to center on the center of the window */
  margin: 0;
  display: grid;/*or */  /* display:flex;*/  /*also works*/
  min-height: 100vh;
}

figure {
  background:yellow;
  /* center x,y*/
  margin: auto;
  /* without a flex or grid parent, make it a block that can shrink and center horizontally
  display:block; */
  
  /* shrink to the single widest content */
  width: min-content;
  /* or/and  instead  block
  display:table;
  width:0;
  */
}
<figure>
  <img src="https://dummyimage.com/100">
  <figcaption>This is a longer caption that may wrap lines untill a word is wider than the image itself.</figcaption>
</figure>
G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129