How to show a region on a image with CSS

和自甴很熟 提交于 2019-12-12 01:18:55

问题


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


回答1:


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, either

  • Have the image be the div's background-image (you can even position it using background-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 the display: inline-block property (Not supported by older IEs).




回答2:


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 like background:url("sprite.png") 0 0;. To use another portion of the sprite e.g. at another child element, you can define background:url("sprite.png") -125 0;.




回答3:


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:

img 
{
position:absolute;
clip:rect(0px,125px,125px,0px);
}



回答4:


Put your image inside div

<div style="width: 125px; height: 125px; overflow: hidden;">
    <img src="..." />
</div>


来源:https://stackoverflow.com/questions/3708234/how-to-show-a-region-on-a-image-with-css

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!