避免拉伸图像 css

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

Avoid stretch on image css

cssimage

提问by Zincktest

I am rendering an image into my div. I want to avoid stretching of my image.

我正在将图像渲染到我的 div 中。我想避免拉伸我的图像。

    div {
           height: 300px;
           width: 300px; 
        }
    img {
           min-width: 300px;
           min-height: 300px;
           max-height: 300px;   
        }

My problem is, that my image strecthes on the width. I want to be normal width, even though some of the image will miss.

我的问题是,我的图像在宽度上拉伸。我想要正常宽度,即使有些图像会丢失。

   div {
           height: 300px;
           width: 300px; 
           overflow: hidden;
        }
    img {
           height: 300px
           max-width: none;
           min-width: 300px;
        }

I solved it.

我解决了。

回答by ZombieCode

I would forget setting the min-height and the max-height. Just set the height to be 300 pixels and put an overflow hidden on the div tag. That way no matter what the image size it will always stay in proportion and never go outside the boundaries of your div tag.

我会忘记设置最小高度和最大高度。只需将高度设置为 300 像素并将溢出隐藏在 div 标签上。这样无论图像大小如何,它都将始终保持成比例,永远不会超出 div 标签的边界。

div { height: 300px; width: 300px; overflow: hidden; }
img { height: 300px; }

回答by Al Amin

You can achieve this with simply adding object-fit: cover;. An example might be like -

您只需添加object-fit: cover;. 一个例子可能是这样的 -

img {
    height: 300px
    width: 100%;
    object-fit: cover;
}

回答by Shomz

Put the image as the div background if you want to avoid stretching the easiest way (yet maintain the original width).

如果您想避免以最简单的方式拉伸(但保持原始宽度),请将图像作为 div 背景。

回答by Jyothish Kumar

just specify max-width 100% and height :auto

只需指定最大宽度 100% 和高度 :auto

回答by justisb

Use max-widthinstead of min-width, and just set heightto 300px(or only use max-height).

使用max-width代替min-width,并设置height300px(或仅使用max-height)。

回答by snumpy

You can use overflow:hiddento hide any portion of the image outside of the width of the div.

您可以使用overflow:hidden隐藏 div 宽度之外的任何图像部分。

div {
       height: 300px;
       width: 300px; 
       overflow: hidden;
    }
img {
       /*min-width: 300px;*/
       height: 300px;   
    }