简体   繁体   中英

Floating figure with figcaption matching image width. CSS solution that works in both Firefox and Chrome

Basically I have a floating image, which has some arbitrary size based on the image being loaded (capped to some max-width %), with a caption below. (In the examples, I set a fixed size just for demonstration.)

Initially, I had a problem getting the figcaption to auto-fit to the size of the image above it. I used the display: table-caption style to get that to work in Firefox, but it breaks in Chrome.

<div>
  <figure>
    <img />
    <figcaption>This is some text. This is some text. This is some text. This is some text. This is some text.</figcaption>
  </figure>
</div>
div {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
figure {
  position: relative;
  max-width: 85%;
  margin: auto;
  display: block;
}
img {
  width: 300px;
  height: 150px;
  background: #000;
}
figcaption {
  display: table-caption;
  caption-side: bottom;
  width: 100%;
}

https://jsfiddle.net/45jk62s8/

In Chrome, for me, the figcaption looks all scrunched up, not the same width as the image.

If I change the figure element to display: table , it works in Chrome but not Firefox.

figure {
  display: table;
}

https://jsfiddle.net/45jk62s8/1/

In Firefox, for me, the figure is no longer horizontally centered and the figcaption width is not constrained. I tried width: fit-content but that doesn't work since the figcaption is allowed to run long.

I assume it has something to do with the wrapper div I use to center the figure, but I can't figure out a cross-browser solution to this at the moment. The figure does need to be fixed and centered, such that even if the behind content is scrollable, the figure is always centered in the page.

This CSS seems to create the desired output in Firefox and Chrome. It uses table , table-cell and table-caption for all the components and removes the 100% width on the caption.

div {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  display: flex;
  align-items: center;
  justify-content: center;
}
figure {
  position: relative;
  max-width: 85%;
  margin: auto;
  display: table;
}
img {
  width: 300px;
  height: 150px;
  background: #000;
  display: table-cell;
}
figcaption {
  display: table-caption;
  caption-side: bottom;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM