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.
我有很多不同大小的图像(300x400,500x300 ......)。我想在固定大小的div中显示那些正确缩放的大图像。
For example, I have a 200x200 div, and a 500*300 image.
例如,我有一个200x200 div和一个500 * 300图像。
|--------------------|
| |
| |
| 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.
因此,图像的宽度将为200像素,高度将按比例缩放,并变为300 * 200/500 = 125像素。图像看起来会更小,但它保持比例并且看起来仍然很好。
|--------------------|
| Blank |
|--------------------|
| |
| Image(200x125) | # div (200x200)
| |
|--------------------|
| Blank |
|--------------------|
How can I do that? Is there any javascript libs to do this?
我怎样才能做到这一点?有没有javascript库可以做到这一点?
3 个解决方案
#1
1
You need to use max-width
and max-height
css properties to the img
tag.
您需要对img标记使用max-width和max-height css属性。
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.
当我们不知道图像的宽度和高度时,我建议使用以下css代码,它会自动对齐父容器中的图像。
.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:
使用background css属性执行相同操作:
#2
1
.divclass img {
max-width: 100%;
}
#3
0
HTML:
<div class="outerDiv">
<img src="imagename.jpg" class="img">
</div>
CSS:
.img{
max-width:100%
}
Hope this helps
希望这可以帮助
#1
1
You need to use max-width
and max-height
css properties to the img
tag.
您需要对img标记使用max-width和max-height css属性。
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.
当我们不知道图像的宽度和高度时,我建议使用以下css代码,它会自动对齐父容器中的图像。
.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:
使用background css属性执行相同操作:
#2
1
.divclass img {
max-width: 100%;
}
#3
0
HTML:
<div class="outerDiv">
<img src="imagename.jpg" class="img">
</div>
CSS:
.img{
max-width:100%
}
Hope this helps
希望这可以帮助