开发者

How to show a region on a image with CSS

I have a 125x250 image and I need to just display a 125x125 region of i开发者_如何转开发t.

Can I do this via CSS? How?

Thank you


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).


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;.


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);
}


Put your image inside div

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜