How to best fit a figure with image and caption inside a DIV with CSS, or Angular

1.7k views Asked by At

How to best fit a <figure> inside a <div>? The figure may contain an <img> and <figcaption>. Both CSS or Angular approaches are welcomed.

<div class="container-wrapper">
  <figure>
    <img src="" alt="">
    <figcaption>This is figure caption</figcaption>
  </figure>
</div>

The figure must be at the center, and always fill 100% height or width, depending on the img orientation (portrait or landscape).

The div container does not have a fix size, its size is dynamic too.

Auto fit figure in div

1, 2, 3 - Try to best fit with either "100% height" or "100% width", depending on the situation (and still centering within the DIV)

4 - If a figure without caption, and both the container and the image have the same aspect ratio, then the image will fit perfectly

5 - Although the container and the image have the same aspect ratio, however, since caption is available, the image will be slightly adjusted to allow the caption to fit beautifully inside the DIV

6 - Without image, the caption-only-figure still can fit in the container

** NOTE: IMAGE MUST NOT BE STRETCH ** (maintain its original aspect ratio)

Either CSS or Angular approaches are welcomed.

I try a lot methods related to CSS, some of them work only for single <img> element, but none of them work perfectly for <img>+<figcaption> method, may somebody please advice?

Regarding Angular method, I thought of implementing a directive, something like "autoFitImage" directive:

<div class="container-wrapper" autoFitImage>
  <figure></figure>
</div>

But temporarily don't have a concrete solution, may somebody please advice?

0

There are 0 answers