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

tsl*_*lmy 8 html css

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

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

例如,如果我有一个图像的文件原来如下所示:

____8888________
____8888________
____8888________
Run Code Online (Sandbox Code Playgroud)

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

____8888________
____8888________
____8888________
Run Code Online (Sandbox Code Playgroud)

一旦我使浏览器变得更窄,max-width(在这个例子中假设10个字符)就会生效.
当发生这种情况时,我希望它是:

____8888__
____8888__
____8888__
Run Code Online (Sandbox Code Playgroud)

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

__888_____
__888_____
__888_____
Run Code Online (Sandbox Code Playgroud)
  • 任何技巧(把它放到<div>背景中)都没关系.
  • 宽度和高度未知.
  • 谢谢大家对你以前的答案,但是,对不起,我想我还没有把足够的重点放在" ,之前这意味着限制了其宽度与页面的40%"宽度限制它应该看起来正常.

小智 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*/
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
   <img src="http://i.stack.imgur.com/fv6Ib.jpg" alt="Beach Scene" class="stretchy" />
</div>
Run Code Online (Sandbox Code Playgroud)

如果要以任何方式剪切/裁剪图像,请将其设置为大于其父级,并将父级的溢出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;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
   <img src="http://i.stack.imgur.com/fv6Ib.jpg" alt="Beach Scene" class="clipped" />
</div>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助...


Man*_*vin 7

将此类添加到 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;
}
Run Code Online (Sandbox Code Playgroud)