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

时间:2012-01-13 06:27:08

标签: html css

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

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

例如,如果我的图像的文件最初如下所示:

____8888________
____8888________
____8888________

在我的网页中,通常看起来应该是:

____8888________
____8888________
____8888________

只要我将浏览器缩小一点,max-width(在本例中为10个字符)就会生效。
当发生这种情况时,我希望它是:

____8888__
____8888__
____8888__

(就像它从右侧切割而来。当然从双方都更好),
而不是:

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

5 个答案:

答案 0 :(得分:14)

诀窍是将图像放入包含块元素,例如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设置为隐藏。

示例:

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>

希望这会有所帮助......

答案 1 :(得分: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;
};

答案 2 :(得分:2)

将此类添加到img html标记中,它将保持图像不变,但是将采用必要的指定空间ie.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 :(得分:0)

尝试使用ImageResizer。 这是链接:http://imageresizing.net/

答案 4 :(得分:-1)

你的意思是剪裁图像?如果是这样看看CSS溢出属性。您也可以将其置于背景中并将其置于div

中心
相关问题