2

Given a HTML snippet

<div class="swiper-slide">
  <div layout="row" layout-align="start stretch" flex style="height: 100%;">
    <div layout="row" layout-align="center center" flex="grow">
      <img src="/media/{{mediaId}}/h/1440">
    </div>
  </div>
</div>

and it's CSS as

img {
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
}

The image does remain centered and does not grow beyond it's parent container, however it does horizontally stretch or shrink when the component is resized. Is it possible to tell that the image element should preserve the aspect ratio of the displayed image?

J.vee
  • 623
  • 1
  • 7
  • 26
  • 2
    Try changing only the width OR height, not both – j08691 Oct 09 '18 at 13:46
  • this will result in either height or width to go outside of the parent, unfortunately. – Yanick Rochon Oct 09 '18 at 13:48
  • You may find this helpful as I think it contains the solution: [Child with max-height: 100% overflows parent](https://stackoverflow.com/questions/14262938/child-with-max-height-100-overflows-parent) – ThisClark Oct 09 '18 at 14:03
  • Your code as shown appears to work correctly for me on Firefox. – Martin Oct 09 '18 at 14:49
  • However I would highly recommend you remove your inline `style`. This will be a factor in causing your problem. – Martin Oct 09 '18 at 14:50

2 Answers2

1

Display the image as a background of a container block, that's stretched to your desires.

Something like this:

<div class="swiper-slide">
  <div layout="row" layout-align="start stretch" flex style="height: 100%;">
    <div layout="row" layout-align="center center" flex="grow">
      <div 
        class="img-container" 
        style="background-image: url(/media/{{mediaId}}/h/1440)"
      >
      </div>
    </div>
  </div>
</div>

CSS:

.img-container {
  width: 100%;
  height: 100%;
  background-size: cover;
  background-repeat: no-repeat;
}

This way you can ensure the image doesn't stretch only in one direction, making it look off, but instead keeps the ratio.

Gabriel C. Troia
  • 3,180
  • 2
  • 16
  • 17
0

Use stretch on the max-height, it won't work in old browsers you would have to do some hacky css for those.

img {
  display: block;
  max-width: 100%;
  max-height: -webkit-fill-available;
  max-height: -moz-available;
  max-height: fill-available;
  border: 1px solid blue;
}

.container {
  border: 1px solid red;
  width: 300px;
  height: 300px;
  padding: 5px;
  margin-bottom: 20px;
}
<div class="container"><img src="https://cdn.vox-cdn.com/thumbor/LjOG9-WQDquskHMvYG32ADEaDm4=/0x0:2040x1360/920x613/filters:focal(857x517:1183x843):format(webp)/cdn.vox-cdn.com/uploads/chorus_image/image/57358643/jbareham_170504_1691_0020.0.0.jpg" /></div>

<div class="container"><img src="https://designyoutrust.com/wp-content/uploads/2018/06/0-24.jpg" /></div>
Dominic
  • 62,658
  • 20
  • 139
  • 163