Html 修复图像大小而不重新调整大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10196926/
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-28 23:51:42  来源:igfitidea点击:

fix image size without re-sizing

imagehtmlimage-processingresizeslideshow

提问by andrew anderson

I have a divwhich is width:500px;and height:170px;

我有一个divwidth:500px;height:170px;

The divcontains a jqueryslideshow which gets random images from my database and displays them.

div包含jQuery的幻灯片,从我的数据库,并显示他们得到随机图像。

Problem is that the images are uploaded by users and can be any aspect-ratio/any size.

问题是图像是由用户上传的,可以是任何纵横比/任何大小

I need the images to fit the divwithout being resized using

我需要图像以适应div而不使用调整大小

style='height:x; width:x;

Basically, I want all images to be displayed properly and in acutal quality.

基本上,我希望所有图像都能以实际质量正确显示。

I don't want to restrict which sizes of images can be uploaded as they as displayed in other parts of the site in full size/quality.

我不想限制可以上传的图像尺寸,因为它们以全尺寸/质量显示在网站的其他部分。

Can any provide a solution?

任何人都可以提供解决方案吗?

回答by Richard A

You could use CSS to set the size of the images in the slideshow without necessarily changing the aspect ratio of the image.

您可以使用 CSS 来设置幻灯片中图像的大小,而不必更改图像的纵横比。

  • set the height of the image to the height of the slideshow container

  • make the width auto so it maintains its aspect ratio

  • set a max-width so it doesn't get wider than the slideshow

  • 将图像的高度设置为幻灯片容器的高度

  • 使宽度自动以保持其纵横比

  • 设置最大宽度,使其不会比幻灯片更宽

slideshow.img{
    height:170px
    width:auto;/*maintain aspect ratio*/
    max-width:500px;
}

Note the images might be slimmer than the slideshow if the original size is small.

请注意,如果原始尺寸较小,图像可能会比幻灯片更薄。

回答by Corey Docken

You should be able to use CSS's max-widthproperty. You won't want to specify the width or height if you do this.

您应该能够使用 CSS 的max-width属性。如果您这样做,您将不想指定宽度或高度。

Your HTML:

你的 HTML:

<div id="yourContainer">
    <img src="imagePath" />
</div>

And your CSS:

还有你的 CSS:

#yourContainer {
    width: 500px;
    height: 170px;
}

#yourContainer img {
    max-width: 100%;
    max-height: 100%;
}

This won't centre your image inside of the container, but it should get the job done for you.

这不会使您的图像在容器内居中,但它应该为您完成工作。

回答by WaleedBarakat

I have figured out how to accomplish image resize keeping aspect ratio and centering the image with simple piece of CSS code as follow:

我已经想出了如何使用简单的 CSS 代码来完成图像调整大小保持纵横比并使图像居中,如下所示:

width: auto !important; /*Keep the aspect ratio of the image*/
height: 140px !important;
margin: 0 auto 1em auto; /*Center the image*/

Hope this help someone :)

希望这有助于某人:)