使用CSS来缩放和重新定位div中的图像?

时间:2010-05-02 04:30:31

标签: html css resize scale

我们知道如何使用CSS在div中仅显示图像的部分(即图像精灵),但图像必须是背景图像。

我们知道如何使用CSS来缩放图像,但图像必须是IMG。

有没有人知道缩放和成像的方法,只展示其中的一部分?

例如,我想:

  1. 显示像素(15,15)到(100,100)和
  2. 将它扩大200%。
  3. 我可以通过在背景图像中制作第一个。第二个我可以通过使它成为前景图像。但到目前为止,我还没有确定如何做到这两点。甚至可以只使用CSS / HTML吗?

1 个答案:

答案 0 :(得分:6)

您可以像平常一样缩放图像。然后,使用容器div来裁剪图像。要设置裁剪矩形的位置,请在图像上使用position: relative(而不是包含div)。以下是使用stackoverflow徽标的示例:

<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>
相关问题