I am trying to make images fit inside black border div whether they rotate or not. I have tried overflow:hidden, max-height:100% and object-fit: contain but still images overflow. with transform. I don't know what to try next. Need Help
<div style="border: 1px solid">
<img img-fix-orientation="model.post.image" ng-src="{{model.post.image ? model.post.image : model.post.sub_category.name == 'Service' ? 'images/service.png' : 'images/thing.png'}}" style="max-width:100%;" alt="post image" />
</div>

Note, object-fit lacks good browser support, and there are options to over come that, though here I want to show how contain applies with and w/o transform.
To show an image in an img element uncut, you use the object-fit: contain, set width and /or height to 100% and it will make both vertical and horizontal images fit with no overflow.
.wrapper {
display: inline-block;
height: 150px;
width: 250px;
padding: 5px;
margin: 5px;
background: lightgray;
}
.wrapper img {
height: 100%;
width: 100%;
object-fit: contain;
}
<div class="wrapper">
<img src="http://placehold.it/150x300/f00"/>
</div>
<div class="wrapper">
<img src="http://placehold.it/300x150/00f"/>
</div>
Now, when you apply transform: rotate(90deg) it is only visually it does that, so from the document flow perspective, it still is sized/positioned as in the above sample.
This means neither the wrapper nor img are aware of any changes and therefore one get the overflow when rotate a horizontal img, to vertical, in a horizontal wrapper.
To be able to rotate such img and make it fit vertically, the transform needs to know the aspect ratio of the wrapper before hand, to be able compensate the overflow, and in this sample it is known (150px / 250px = 0.6), so by adding scale to the transform we can avoid an overflow.
.wrapper {
display: inline-block;
height: 150px;
width: 250px;
padding: 5px;
margin: 5px;
background: lightgray;
}
.wrapper img {
height: 100%;
width: 100%;
object-fit: contain;
transform: rotate(90deg) scale(0.6);
}
<div class="wrapper">
<img src="http://placehold.it/300x150/00f"/>
</div>
For a vertical img in a vertical wrapper one need to apply the same fix.
The div must have a set width and height to know what to consider overflow.
If you say the div is 500px wide, then the overflow will apply.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With