Make element same width as dynamically sized image?

后端 未结 5 1322
逝去的感伤
逝去的感伤 2021-02-18 23:59

I have a responsive slideshow-type layout with captions below each image.

I\'m attempting to get the caption to be the same width as the image. The problem is that the i

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-19 00:32

    There's a very little known CSS property that's made for what you require: min-content. What this does, is:

    • Uses intrinsic value, meaning it adapts to it's content.
    • Reduces the width of the container automatically so that an image fits inside it perfectly.
    • If text content needs to wrap inside the container, it should.

    Read this article: Design From the Inside Out With CSS Min-Content

    There is one thing I'm not crazy about is the prefixes:

    width: -moz-min-content;
    width: -webkit-min-content;
    width: min-content;
    

    I added some resets and commented on which styles are:

    • Optional
    • Recommended
    • Required

    Important CSS

      figure {
         height: 100%;
         width: -moz-min-content;
         /* REQUIRED */
         width: -webkit-min-content;
         /* REQUIRED */
         width: min-content;
         /* REQUIRED */
      }
    

    DEMO: https://plnkr.co/edit/6e1hYkK6lB2KVS3uvQy2?p=preview

    BONUS: https://plnkr.co/edit/gahMFQScxQtkweo1G2jD?p=preview

    I have made the captions longer and added the following CSS to show how you can wrap your captions and not breakout or extend the figcaption.

    CSS Bonus

    figcaption * {
      white-space: pre-wrap;
      /* RECOMMENDED */
    }
    

    Although not a requirement, I assume that in the near future you'll want to have captions that wrap without any hassle. I reviewed the others:

    • LGSon's will actually extend the image and figcaption, easily fixed with my solution I'm guessing.

    • guest271314's extends text overflow, I'm not sure what would fix that since it's not a container.

    • Ryan Litte's extends the figcaption, I believe that my solution could probably fix that as well.

提交回复
热议问题