CSS:强制图像宽度和高度无拉伸 [英] CSS: force image width and height without stretching

查看:272
本文介绍了CSS:强制图像宽度和高度无拉伸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有:

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

然后

<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>

#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; }

这篇关于CSS:强制图像宽度和高度无拉伸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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