我们知道如何使用 CSS 仅显示div 中的图像的一部分(即图像精灵),但图像必须是背景图像。
我们知道如何使用 CSS 来缩放图像,但图像必须是 IMG。
有谁知道缩放和图像并仅显示其中一部分的方法?
例如,我想:
- 显示像素 (15,15) 到 (100,100),以及
- 将其扩大 200%。
第一个我可以通过制作背景图像来完成。第二个我可以通过使它成为前景图像来做到这一点。但到目前为止,我还没有确定如何做到这两点。甚至可以只使用 CSS/HTML 吗?
您可以像往常一样缩放图像。然后,使用容器 div 裁剪图像。要设置裁剪矩形的位置,position: relative
请在图像上使用(而不是包含 div)。下面是一个使用 stackoverflow 的 logo 的例子:
<style type="text/css">
div {
/* Set size of crop area. Setting its location happens bellow. */
width: 150;
height: 100;
overflow: hidden; /* Crop it like it's hot! */
/* not part of the implementation; only to display what's going on */
border: 1px solid black;
background-color: #ddd;
}
img {
/* Set the crop location by shifting the image
* up by 70px and to the right by 30px.
*/
position: relative;
top: -70px;
left: 30px;
/* Scale the image as you normally would. */
width: 300px;
height: 150px;
}
</style>
<div>
<img src="http://sstatic.net/so/img/logo.png">
</div>