tags:

views:

75

answers:

4

Hi
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

+5  A: 

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

Pekka
*dispaly: inline; *zoom: 1; is the solution for display: inline-block in IE<8
Happy
Thank you very much
Snigger
+1  A: 

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);
}
Edd Turtle
+1  A: 

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

MaoPU
Thanks for information very much.
Snigger
+1  A: 

Put your image inside div

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