如何使用 CSS 在图像上显示区域
我有一个 125x250 的图像,我只需要显示它的 125x125 区域。
我可以通过 CSS 做到这一点吗?如何?
谢谢
I have a 125x250 image and I need to just display a 125x125 region of it.
Can I do this via CSS? How?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有 CSS
clip
属性,但它有点笨拙正如@edd 在他的回答中指出的那样,设置仅适用于绝对和固定定位的图像。我个人会创建一个 125x125
div
,并且根据情况,让图像成为 div 的
background-image
(您甚至可以使用background-position
将图像,并给
div
overflow:hidden
(优点:它仍然是一个带有 ALT 文本的图像元素)如果你需要整个东西像文档中的图像一样流程中,您可以为
div
赋予display: inline-block
属性(旧版 IE 不支持)。There is the CSS
clip
property but it's a bit clunky to set up and, as @edd points out in his answer, works for absolutely and fixedly positioned images only.I personally would create a 125x125
div
and, depending on the situation, eitherHave the image be the div's
background-image
(you can even position it usingbackground-position
Put the image in it, and give the
div
overflow: hidden
(advantage: It will still be an image element with an ALT text)If you need the whole thing to behave like an image in the document flow, you can give the
div
thedisplay: inline-block
property (Not supported by older IEs).这种技术也称为“精灵”。 2004 年的 ALA 文章 演示了基础知识,可以在 w3schools 找到另一篇精彩而简短的介绍(www.w3schools.com/css/css_image_sprites.asp)。
所以它基本上是一个相对定位的父元素。子元素具有定义的大小和背景,例如
background:url("sprite.png") 0 0;
。要使用精灵的另一部分(例如在另一个子元素上),您可以定义background:url("sprite.png") -125 0;
。This technique is also called "sprites". An ALA article from 2004 demonstrated the basics, another good and short introduction can be found at w3schools (www.w3schools.com/css/css_image_sprites.asp).
So it is basically a parent element being positioned
relative
. A child element has a defined size and a background likebackground:url("sprite.png") 0 0;
. To use another portion of the sprite e.g. at another child element, you can definebackground:url("sprite.png") -125 0;
.您可以使用 CSS Clip 属性,但设置起来有点繁琐,因为图像和父级需要是绝对位置或固定位置。但一旦设置,它确实可以很好地工作。
例子:
You can use the CSS Clip property but it's a bit fiddly to set up because the image and parent need to be either absolute of fixed positioned. But it does work quite well once setup.
example:
将图像放入
div
中Put your image inside
div