[英]Resize image using only html and css
我有一个高度为173px,宽度为157px的图像。我想将其高度和宽度设置为100 px,但是当我这样做时它会被拉伸。我想使用img标签来做到这一点。调整大小
Give height:auto
when you change it's width. 给定height:auto
当您更改宽度时。 Write like this: 这样写:
img{
width:100px;
height:auto;
}
Yes, it's stretched. 是的,它很拉伸。 How do you want to do without stretching ? 你想怎么做而不会伸展?
The only thing you can do is to recreate an image using a server api and do not use the resize in css. 您唯一可以做的就是使用服务器api重新创建映像,并且不要在CSS中使用调整大小。
But, it will strecht because you do not kept the ratio between width and height ! 但是,这样做会很困难,因为您没有保持宽高比!
Yes, it gets stretched when you apply a different multiplication factor in the horizontal direction than in the vertical. 是的,当您在水平方向上应用与垂直方向上不同的乘法因子时,它将被拉伸。 You may want to try width:auto
or heigth:auto
. 您可能需要尝试width:auto
或heigth:auto
。
Edit: or if you don't have a problem with cropping the image, you can put it in a container element (for instance a div), on which you set overflow:hidden
. 编辑:或者如果您对裁剪图像没有问题,可以将其放在容器元素(例如div)中,在该容器元素上设置overflow:hidden
。
<div style="width:100px; height:100px; overflow:hidden">
<img src="your image" alt="" style="width:100px; height:auto" />
</div>
Another edit: Just realised it's possible to crop it using only CSS on the image (and not needing a parent container), by using the clip
property. 另一个编辑:刚刚意识到可以通过使用clip
属性在图像上仅使用CSS裁剪(而无需父容器)。 See W3C page . 参见W3C页面 。
However, sadly enough that requires the element to be absolutely positioned, so unless you know exactly where in the window you want to put it, you'll have to put it in a parent container anyway. 但是,可悲的是,它要求将元素绝对定位,因此,除非您确切知道要在窗口中放置的位置,否则无论如何都必须将其放置在父容器中。 Oh well. 那好吧。
I don't believe it can be accomplished with the img
-tag, as it will stretch the image according to your provided width/height. 我不认为可以使用img
-tag来完成此操作,因为它会根据您提供的宽度/高度来拉伸图像。 It would however be possible to use a div
-element instead, and assign the image as a background. 但是,可以改用div
-element并将图像分配为背景。 That way the image will not be re-sized, the parts of the image not possible of to display within your 100x100 px element will appear "cropped". 这样一来,图片将不会调整大小,无法在100x100 px元素中显示的图片部分将显示为“已裁剪”。
.image-element
{
background-image: url('yourimage.png');
width: 100px;
height: 100px;
}
By using the background-position
attribute you could also control which parts of the image that gets "cropped". 通过使用background-position
属性,您还可以控制图像的哪些部分“被裁剪”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.