如何设置图像的宽度和高度而不伸展它? [英] How to set an image's width and height without stretching it?

查看:87
本文介绍了如何设置图像的宽度和高度而不伸展它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有:

If I have:

#logo {
    width: 400px;
    height: 200px;
}

然后

then

<img id="logo" src="logo.jpg"/>

会拉伸以填充该空间。我希望图像保持相同的大小,但要占用DOM中的这么多空间。是否必须添加封装的< div> < span> ?我讨厌为样式添加标记。

will stretch to fill that space. I want the image to stay the same size, but for it to take up that much space in the DOM. Do I have to add an encapsulating <div> or <span>? I hate adding markup for styling.

推荐答案

是的,你需要一个封装的div:

Yes you need an encapsulating div:

<div id="logo"><img src="logo.jpg"></div>

类似于:

with something like:

#logo { height: 100px; width: 200px; overflow: hidden; }

其他解决方案(填充,边距)更乏味(因为您需要计算正确的值基于图像的尺寸),但也没有有效地允许容器比图像小。

Other solutions (padding, margin) are more tedious (in that you need to calculate the right value based on the image's dimensions) but also don't effectively allow the container to be smaller than the image.

此外,上述可以更容易地适应不同的布局。例如,如果您想要右下角的图片:

Also, the above can be adapted much more easily for different layouts. For example, if you want the image at the bottom right:

#logo { position: relative; height: 100px; width: 200px; }
#logo img { position: absolute; right: 0; bottom: 0; }

这篇关于如何设置图像的宽度和高度而不伸展它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆