3

我所拥有的:
我有一个宽度为 200 像素 X 200 像素的 div,
其中的图像大小为 400 像素 X 400 像素。

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

到目前为止我所做的:
小提琴:http: //jsfiddle.net/5Hbr3/1/

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

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

谢谢

4

2 回答 2

9

position: relative在父元素和position: absolute子图像上使用。

#sample {
  width: 200px;
  height: 200px;
  overflow: hidden;
  position: relative;
  border: 1px solid black;
}

#sample img {
  position: absolute;
  top: -100px;
  left: -100px;
}
<div id="sample">
  <img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBg8PDw8QEBQREA8PEBAQEA8NDhAQEA4PFRAVFBgQEhQXHSYfFxkjGRISHy8gIycpLiwtFR8xNTAqNSYrLCkBCQoKDgwOGg8PGiwkHiUsLSkuLCktLCwsLSoqKSwsLS0tLCwsLCwsKSksLCwsKSksLCksLCwsLiksKS0sKSwsLP/AABEIAOEA4QMBIgACEQEDEQH/xAAcAAEAAQUBAQAAAAAAAAAAAAAAAwECBAUGBwj/xABAEAACAQICBwQHBgQFBQAAAAAAAQIDEQQSBQYTITFBUWFxgZEiMkJSobHBBxQVI1NyM2LR8EOCkqLhY3ODk/H/xAAbAQABBQEBAAAAAAAAAAAAAAAAAQIEBQYDB//EADMRAAIBAwEEBwgDAAMAAAAAAAABAgMEETEFEhMhIkFRYXGBkQYyUqGx0eHwFELBFSPx/9oADAMBAAIRAxEAPwD3EAAAAAAAAAAFG7b3uS5vkc1pjXmhRvGj+dUW66dqcX2y5+A2U4xWWdaVGpWe7BZOmNTj9acJQupTUpL2aXpv4bl4s890nrFicTfaTeX9OHow8UuPjc11yHO6+FF3R2P11ZeS+52mL+0N8KVJLpKrK7/0r+pqcRrjjJ/4igulOEV8XdmhzDMR5VpvrLOFhbw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T32Xp3ng5W57Cq93dCfLud+89BAyUFLU51KUai6SPBMfo6th55K8JUpclNWUv2vg/Ax0z37E4WnVi4VIxqQfGM4qUX4M5XSf2Z4Srd0XLDyfKPp0/wDS+Hg0RpW76iBOzkvdeTy1MqmdTjvs0x1O+z2dePLJLJN/5ZbviaLFaCxdH+JQrR7dnJrzV0cHCS1RFlSnHVGImZGj8G69WMFw4yfSK4v++piSlbju79x1ugcBsqeaS/MqWcuqXKPx+JAvK/AptrV8l+9xKsbX+RV3Xoub/e82kIqKUVuSSSS5Jcg5FrkW5jKY7TaJYLnIo5F9LCVZ+rCcu6LsZ+H1axE+KjBfzy3+SuS6VpVqe5Bvy/3QZKpCOrNXmLqVKU3linKT5RV2dPhdU6cd9STm+i9GP9TcYfDQpq0IqK6RVvMt6GxakudV7q9X9vqRZ3kV7vM5zR+qsnaVZ5V7kd8n3vkdHhsLClHLCKiui+b6koNBbWdK3XQXPt6yBUrTqe8wACWcgAAAAAAAAAAAAAAAAAAAAAAAAAAAAADmdZ/VZqJcF/fMAz+2fdiS7L3peRSHB9z+RvtD8F4fIA5bI1O91odAADSlaAAAAAAAAAAAAAAAAAAAAf/Z"
  />
</div>

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

于 2013-04-03T05:47:25.673 回答
6

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

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

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

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

于 2013-04-03T06:26:11.210 回答