CSS 如何隐藏部分图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11092146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to hide part of the image?
提问by xRobot
I need to do this:
我需要这样做:
if the image has an height higher of 100px then hide the rest of the image ( example: image with height of 80px -> show full image, image with height of 150px -> show only the first 100px ).
如果图像的高度高于 100 像素,则隐藏图像的其余部分(例如:高度为 80 像素的图像-> 显示完整图像,高度为 150 像素的图像-> 仅显示前 100 像素)。
Is there a way to do that with CSS ?
有没有办法用 CSS 做到这一点?
回答by Karl Nicoll
You can use the max-height
property to specify the maximum height of the image, and then use overflow: hidden;
to hide anything else.
您可以使用该max-height
属性指定图像的最大高度,然后用于overflow: hidden;
隐藏其他任何内容。
e.g.
例如
HTML:
HTML:
<div class="image-container">
<img src="some-image.jpg" />
</div>
CSS:
CSS:
.image-container {
max-height:100px;
overflow:hidden;
}
JSFiddle Sample: http://jsfiddle.net/3jA9q/
JSFiddle 示例:http: //jsfiddle.net/3jA9q/
EDIT
编辑
For internet explorer 6, you can use CSS expressionsto emulate something similar:
对于 Internet Explorer 6,您可以使用CSS 表达式来模拟类似的内容:
.image-container {
height:expression(this.scrollHeight<100?"auto":"100px");
overflow:hidden;
}
Do note however that this requires that the user have JavaScript enabled in their browser. My experience with CSS expressions however have been pretty poor, and they're best avoided.
但是请注意,这要求用户在其浏览器中启用 JavaScript。然而,我对 CSS 表达式的体验非常糟糕,最好避免使用它们。
回答by John Stimac
You can do it using a combnation of max-height
and overflow
.
您可以使用max-height
and 的组合来完成overflow
。
HTML:
HTML:
<div>
<img>
</div>
CSS:
CSS:
div{
max-height:100px;
overflow:hidden;
}
Also note that max-height
doesn't work in older browsers, but if you used normal height
then images could never be shorter than 100px either.
另请注意,max-height
这在较旧的浏览器中不起作用,但如果您使用普通浏览器,height
则图像也永远不会短于 100 像素。
回答by Brandon
Put it in a div with a height of 100px and set overflow: hidden;
把它放在一个高度为100px的div中并设置 overflow: hidden;