Html 使用css在div中仅显示图像的一部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15779722/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:08:55  来源:igfitidea点击:

Showing only a part of image in div using css

javascripthtmlcssimage

提问by Nagesh Salunke

What I have :
I have a div of width 200px X 200px
and image inside it of size 400px X 400 px.

我所拥有的:
我有一个宽度为 200px X 200px 的 div,
里面有一个大小为 400px X 400 px 的图像。

What I want to do :
I want to show only a part of image inside div Is it possible using only css.If not ? Then what are the other ways
(Note : I don't want to set image to background of the div)

我想要做什么:
我只想在 div 中显示图像的一部分 是否可以仅使用 css.If ?那么其他方法是什么
(注意:我不想将图像设置为 div 的背景)

What I have done so far :
Fiddle : http://jsfiddle.net/5Hbr3/1/

到目前为止我做了什么:
小提琴:http: //jsfiddle.net/5Hbr3/1/

<div id="sample">
    <img src="image.jpg" /> 
</div>

I want to show image from 100,100 to 300,300.
and scrollbar should disappear.
Any help will be appreciated.

我想显示从 100,100 到 300,300 的图像。
和滚动条应该消失。
任何帮助将不胜感激。

Thanks

谢谢

回答by Alfred Xing

Use position: relativeon the parent element and position: absoluteon the child images.

使用position: relative父元素和position: absolute对孩子的图像。

http://jsfiddle.net/5Hbr3/3/

http://jsfiddle.net/5Hbr3/3/

To make the scrollbar disappear, use overflow: hidden(as in the JSFiddle)

要使滚动条消失,请使用overflow: hidden(如在 JSFiddle 中)

回答by psychobunny

Here is a method to tackle your problem:

这是解决您的问题的方法:

http://jsfiddle.net/5Hbr3/5/

http://jsfiddle.net/5Hbr3/5/

#sample{
    background: url(image-data.jpg);
    background-position: -100px -100px;
    width: 200px;
    height: 200px;
}

This method allows you to achieve the same result using one element instead of two, and is also cross-browser compatible. I'd recommend this approach instead of absolutely positioning the image inside the container div.

此方法允许您使用一个元素而不是两个元素来实现相同的结果,并且还跨浏览器兼容。我建议使用这种方法,而不是将图像绝对定位在容器 div 内。