使用 CSS 在 div 内缩放和重新定位图像?

发布于 2024-08-30 16:03:42 字数 303 浏览 5 评论 0原文

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

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

有谁知道一种缩放和图像并仅显示其中一部分的方法?

例如,我想:

  1. 显示像素 (15,15) 到 (100,100),并将
  2. 其放大 200%。

第一个我可以通过制作背景图像来完成。第二个我可以通过将其设为前景图像来完成。但到目前为止,我还没有确定如何做到这两点。是否可以仅使用 CSS/HTML?

We know how to use CSS to show only part of an image within a div (i.e., image sprites), but the image has to be a background image.

We know how to use CSS to scale an image, but the image has to be an IMG.

Does anyone know of a way to scale and image and show only part of it?

For example, I want to:

  1. show pixels (15,15) through (100,100), and
  2. scale it up by 200%.

The first I can do by making in a background image. The second I can do by making it a foreground image. But so far, I have not ascertained how to do both. Is it even possible using only CSS/HTML?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

緦唸λ蓇 2024-09-06 16:03:42

您可以像平常一样缩放图像。然后,使用容器 div 裁剪图像。要设置裁剪矩形的位置,请在图像(而不是包含的 div)上使用 position:relative。以下是使用 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>

You could scale the image just as you would normally. Then, use a container div to crop the image. To set where the crop rectangle goes, use position: relative on the image (not the containing div). Here's an example using stackoverflow's 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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文