Html 有没有办法为图像指定最大高度或宽度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3678378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 04:27:16  来源:igfitidea点击:

Is there a way to specify a max height or width for an image?

htmlcss

提问by Abe Miessler

I'd like to have an image to have either a height of 725 or a width of 500 and maintain it's aspect ratio. When I have images with a height of over 725 and thinner than 500 they get stretched out to fit a width of 500.

我想要一个高度为 725 或宽度为 500 的图像并保持其纵横比。当我有高度超过 725 且小于 500 的图像时,它们会被拉伸以适应 500 的宽度。

What is the best way to do this?

做这个的最好方式是什么?

Below is what I am doing now:

以下是我现在正在做的事情:

<asp:Image Height="725" width="500" ID="img_DocPreview" />

Update:Changed it to this but have the same problem. If I specify just the height it will maintain the aspect ratio but it exceeds the max width of 500px that i want.

更新:将其更改为此,但有同样的问题。如果我只指定高度,它将保持纵横比,但它超过了我想要的最大宽度 500px。

<img style="height:725px;width:500px;" id="img_DocPreview" src="Images/empty.jpg" />

采纳答案by Nico Burns

editied to add support for ie6:

编辑以添加对 ie6 的支持:

Try

尝试

<img style="height:725px;max-width:500px;width: expression(this.width > 500 ? 500: true);" id="img_DocPreview" src="Images/empty.jpg" />

This should set the height to 725px but prevent the width from exceeding 500px. The width expression works around ie6 and is ignored by other browsers.

这应该将高度设置为 725px,但防止宽度超过 500px。宽度表达式适用于 ie6,被其他浏览器忽略。

回答by Daniel Nyamasyo

You can try this one

你可以试试这个

img{
    max-height:500px;
    max-width:500px;
    height:auto;
    width:auto;
}

This keeps the aspect ratio of the image and prevents either the two dimensions exceed 500px

这会保持图像的纵横比并防止两个尺寸超过 500px

You can check this post

你可以看看这个帖子

回答by kbrimington

If you only specify either the height orthe width, but not both, most browsers will honor the aspect ratio.

如果您只指定高度宽度,而不是同时指定两者,则大多数浏览器将遵循纵横比。

Because you are working with an ASP.NET server control, you may consider executing logic on the server side prior to rendering to decide which (height or width) attribute you want to specify; that is, if you want a fixed height under one condition or a fixed width under another.

因为您正在使用 ASP.NET 服务器控件,所以您可以考虑在呈现之前在服务器端执行逻辑来决定要指定哪个(高度或宽度)属性;也就是说,如果您希望在一种条件下具有固定高度或在另一种条件下具有固定宽度。

回答by anand360

set a style for the image

为图像设置样式

<asp:Image ID="Image1" runat="server" style="max-height:1000px;max-width:900px;height:auto;width:auto;" />

回答by Icarin

You could use some CSS and with the idea of kbrimington it should do the trick.

您可以使用一些 CSS 并使用 kbrimington 的想法,它应该可以解决问题。

The CSS could be like this.

CSS 可能是这样的。

img {
  width:  75px;
  height: auto;
}

I got it from here: another post

我从这里得到它:另一个帖子