如何在不拉伸的情况下调整图片大小?

14

我想要一个<img>标签,它的宽度为页面宽度的40%,并且不会被拉伸。

如何调整大小而不拉伸图片?

比如,如果我有一张文件原本是这样的图片:

____8888________
____8888________
____8888________
在我的网页中,通常应该是这样的:
____8888________
____8888________
____8888________

当我将浏览器变窄一些时,max-width(在此示例中为10个字符)会生效。
当发生这种情况时,我希望它是:

____8888__
____8888__
____8888__

(就像被从右侧割掉了一样。当然,从两侧割掉更好),
而不是:

__888_____
__888_____
__888_____
  • 可以使用任何技巧(将其放入<div>的背景中)。
  • 宽度和高度未知。
  • 感谢您之前的回答,但是抱歉,我认为我没有足够强调“在将其宽度限制为页面的40%之后”,这意味着在限制宽度之前,它应该看起来正常。

也许你可以使用JavaScript获取容器/浏览器的宽度和高度,然后计算实际像素,而不是使用百分比。 - Tommy
5个回答

23

诀窍是将图像放置在包含块元素内,例如DIV。一旦放入,将图像的宽度设置为100%,这将指示浏览器将图像宽度与DIV的左右边缘对齐。

然后通过CSS控制DIV的宽度,我发现保持图像在块元素中使得在创建流体布局时更容易进行操作。

示例:

img.stretchy {
width: 100%; /*Tells image to fit to width of parent container*/
}
.container {
width: 33%; /*Use this to control width of the parent container, hence the image*/
}
<div class="container">
   <img src="http://i.stack.imgur.com/fv6Ib.jpg" alt="Beach Scene" class="stretchy" />
</div>

如果您想要对图像进行裁剪或剪裁,请将其设置为大于其父级,并将父级的溢出 CSS 设置为 hidden。
例如:

img.clipped {
    width: 150%; /*Scales image to 150% width of parent container*/
    float: left; /*Floats image to left of container - clipping right hand side*/
    float: right; /*Floats image to right of container - clipping left hand side*/
}
.container {
    width: 33%; /*Use this to control width of the parent container, hence the image*/
    overflow: hidden;
}
<div class="container">
   <img src="http://i.stack.imgur.com/fv6Ib.jpg" alt="Beach Scene" class="clipped" />
</div>

希望这可以帮助到您...


呃......我的意思是,该图像并非原本就被裁剪过(如果我想要裁剪,我会手动编辑图像文件),只有在外部容器变窄时才会出现“裁剪”效果。 - tslmy

7
将此类添加到img html标签中,它将保持图像不变,但将占用必要的指定空间,即40%x 40%,而不会拉伸图像。
.img{
    width:40%;
    height:40%; //change to whatever your choice

/*Scale down will take the necessary specified space that is 40% x 40% without stretching the image*/
    object-fit:scale-down;
}

3
这里有几个选项。(在这里查看所有选项的演示:http://jsfiddle.net/Squeegy/Gcrdu/
第一个选项是未知大小的纯图像。它显示为任何大小。
<img src="http://www.google.com/logos/classicplus.png">

但事实证明,如果你只设置宽度或高度,就可以保留图像的纵横比。另一个维度将自动调整以防止拉伸。

// HTML
<img src="http://www.google.co.jp/logos/classicplus.png" class="aspectshrink">

// CSS
img.aspectshrink {
    width: 100px;
}

但是当您使用CSS背景图像时,可以根据锚点位置进行创意裁剪。
这个文字说“前往”。
// HTML
<div class="cropped-right"></div>

// CSS
.cropped-right {
    width: 100px;
    height: 100px;
    background: url(http://www.google.com/logos/classicplus.png);
    background-position: left center;
    background-repeat: no-repeat;
    border: 1px solid red;
}

而这里是“gle”:

// HTML
<div class="cropped-left"></div>

// CSS
.cropped-left {
    width: 100px;
    height: 100px;
    background: url(http://www.google.com/logos/classicplus.png);
    background-position: right center;
    background-repeat: no-repeat;
    border: 1px solid red;
};

不错的点子,伙计。虽然这不是我的最终答案,但我会将你的回答作为以后裁剪图像的一种方式来参考!谢谢。 - tslmy

0

-1

你是指裁剪图片吗?如果是的话,可以查看CSS overflow属性。此外,您还可以将其放入背景并将其居中在div中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接