Reputation: 8602
I have a lot of large images with different size(300x400, 500x300...). And I want to display those large images properly scaled within a fixed size div.
For example, I have a 200x200 div, and a 500*300 image.
|--------------------|
| |
| |
| div(200x200) |
| |
| |
|--------------------|
|--------------------------------|
| |
| |
| image(500x300) |
| |
| |
| |
| |
|--------------------------------|
So the width of the image will be 200 pixels and height will proportionally scale and become 300 * 200 / 500 = 125 pixels. The image will look smaller, but it keeps its proportions and will still look good.
|--------------------|
| Blank |
|--------------------|
| |
| Image(200x125) | # div (200x200)
| |
|--------------------|
| Blank |
|--------------------|
How can I do that? Is there any javascript libs to do this?
Upvotes: 0
Views: 2341
Reputation: 36
On your fixed div use:
div {
display: flex;
justify-content: center;
align-items: center;
width:200px;
height: 200px;
}
And on your img
use:
img {
max-width: 100%;
max-height: 100%;
}
Upvotes: 0
Reputation: 41832
You need to use max-width
and max-height
css properties to the img
tag.
img {
max-width: 100%;
max-height: 100%;
}
This will keep your image in aspect ratio with respect to its parent container.
When we don't know the image width and height, I suggest to use the following css code, which automatically aligns the image in the parent container.
.image-wrapper {
display: table-cell;
width: 100px;
height:150px;
vertical-align: middle;
border: 1px solid black;
}
.image-wrapper img{
max-width: 100%;
max-height: 100%;
display: block;
margin: 0 auto;
}
Doing the same using background
css property:
Upvotes: 2
Reputation:
HTML:
<div class="outerDiv">
<img src="imagename.jpg" class="img">
</div>
CSS:
.img{
max-width:100%
}
Hope this helps
Upvotes: 0