Home > Blockchain >  How to an shrink image to fit inside of a container with no set width
How to an shrink image to fit inside of a container with no set width

Time:11-17

I have some image cards that each have an image and some text. The size of these cards are determined by the height of the image that they contain. If the viewport width is so small that the set height of the image would make the image overflow horizontally I would like the image to shrink so that it stays within the card/viewport

.card {
  width: fit-content;
  max-width: 100%;
  background-color: lightgray;
  padding: 1em;
}

img {
  height: 13em;
}
<div class="card">
  <img src="https://cdn.sstatic.net/Img/teams/teams-illo-free-sidebar-promo.svg?v=47faa659a05e" alt="random image...">
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I know I can use a media query, but I would like to know if there's a better way to solve this.

CodePudding user response:

I think you have to make your image responsive with max-width. i think this will help

img {
      max-width:100%;
      height: 13em;
    }

CodePudding user response:

While you can set a maximum width of the img to the viewport width this will distort the image if the height is fixed.

To ensure that the width never exceeds the viewport width and the height never exceeds 13em this snippet gives both width and height a maximum. And it does not explicitly set height.

Note: it keeps the padding img within the viewport by setting box-sizing: border-box and by removing any browser default margin and padding also.

<style>
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
.card {
  width: fit-content;
  max-width: 100vw;
  background-color: lightgray;
  padding: 1em;
}

.card img {
  max-height: 13em;
  max-width: calc(100vw - 2em);
}
</style>
<div class="card">
  <img src="https://picsum.photos/id/1016/4000/500" alt="random image...">
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

There are several ways to fit the image to <div>.

img {
    object-fit: cover;
}

The CSS object-fit property is used to specify how an or should be resized to fit its container.

For more details, visit this thread:

  • Related