CSS force image resize and keep aspect ratio
img { display: block; max-width:230px; max-height:95px; width: auto; height: auto;}
<p>This image is originally 400x400 pixels, but should get resized by the CSS:</p><img width="400" height="400" src="http://i.stack.imgur.com/aEEkn.png">
Force an image to fit and keep aspect ratio
You can try CSS3 object-fit
, and see browser support tables.
CSS3
object-fit
/object-position
Method of specifying how an object (image or video) should fit inside
its box. object-fit options include "contain" (fit according to aspect
ratio), "fill" (stretches object to fill) and "cover" (overflows box
but maintains ratio), where object-position allows the object to be
repositioned like background-image does.
JSFIDDLE DEMO
.container { width: 200px; /*any size*/ height: 200px; /*any size*/}
.object-fit-cover { width: 100%; height: 100%; object-fit: cover; /*magic*/}
<div class="container"> <img class="object-fit-cover" src="https://i.stack.imgur.com/UJ3pb.jpg"></div>
How do I auto-resize an image to fit a 'div' container?
Do not apply an explicit width or height to the image tag. Instead, give it:
max-width:100%;
max-height:100%;
Also, height: auto;
if you want to specify a width only.
Example: http://jsfiddle.net/xwrvxser/1/
img {
max-width: 100%;
max-height: 100%;
}
.portrait {
height: 80px;
width: 30px;
}
.landscape {
height: 30px;
width: 80px;
}
.square {
height: 75px;
width: 75px;
}
Portrait Div
<div class="portrait">
<img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>
Landscape Div
<div class="landscape">
<img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>
Square Div
<div class="square">
<img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>
Related Topics
Background Color of Text in Svg
How to Make a Div Expand Vertically to Wrap the Content Within It
How to Make Bootstrap 4 Columns Have a Height of 100%
Vuetify: Fit V-Image Within the Screen Size
How to Set the Height of Vuetify Card
How to Make an Element Fill the Remaining Viewport Height
Angular Material Mat-Drawer in Full Height Flex, Content Overflow Auto
How to Remove Border of Drop Down List:Css
Spring Boot + Thymeleaf CSS Is Not Applied to Template
Cannot Change Font Size of Text Field in Material Ui
Make Nested Div Stretch to 100% of Remaining Container Div Height
Change Button Border Color When the Button Is Being Clicked and After
Simulate Display: Inline in React Native
How to Add Fonts to Create-React-App Based Projects
Change a Html5 Input'S Placeholder Color With Css