Reputation: 2629
I want to show an image in small windows but i need to save on the ratio of the image(I still want that people can know what it is). For example lets say that the image is 1000X200 pixels, and there's a div that defined as: height: 100px; width: 100px; So I want that the image will wrote like that:
<img src="asd.jpg" height=20 width=100 />
and not
<img src="asd.jpg" height=100 width=100 />
or not
<img src="asd.jpg"/>
and then there's scrolls..
I can work with percentages, but how do I do it.. (and does it even work with percentages alone?)
Upvotes: 24
Views: 103288
Reputation: 53821
If your parent div
has a set width
and height
, you could set the max-width and max-height of the img
to 100%
:
div {
width: 100px;
height: 100px;
}
div > img {
max-width: 100%;
max-height: 100%;
}
(It's always a good practice to give images max-width of 100%, for mobile browsers etc.)
Upvotes: 5
Reputation: 3855
If you use javascript, you could simply get the height and width of the image and divide one by the other to get a ratio, then multiply the height and width of the div against that ratio, then set the img dimensions to those numbers.
Obviously that's a very simplistic way to say it, but I'm also not sure if you want to do this with JS or use a strictly CSS solution.
Upvotes: 1
Reputation: 3254
If you set max-height
and max-width
in CSS, modern browsers will restrict it to that size but keep the aspect ratio correct:
<img src="asd.jpg" style="max-height: 100px; max-width: 100px;" />
Upvotes: 56