Home > CSS > Image Clipping with CSS

Image Clipping with CSS

We usually add icons to our web pages. There are a lot of different ways for doing this. For example: We can use background image, we can use unique small image files (Usually, this method is used). However, we will use the best method. Namely, Image Cropping Method using CSS.


This method makes faster our web pages. If we use many unique small image files, number of requests (that we sent to server for each image) will increase. So, loading images takes long time. However, if we use single image including all icons, size of image will increase but number of requests will decrease.

We have an image file named icons.jpg.

Original view of icons.jpg:

Original view of icons.jpg

Structure 1.0:

1
2
3
4
img {
position:absolute;
clip:rect([topcrop],[[leftcrop]+width],[[topcrop]+height],[leftcrop])
}

Example 1.0:We will show only Google Icon.

1
2
3
4
img {
position:absolute;
clip:rect(0px,281px,135px,144px);
}

Leftcrop: 144px, Topcrop: 0px, Width:137px, Height: 135px


Output of Example 1.0:

Google's icon

As you see, Only Google Icon was showed but what is that? The image is still occupying same place. If we don’t want this, we should define image position. Look at example 1.1:


Example 1.1:

1
2
3
4
5
6
img {
position:absolute;
clip:rect(0px,281px,135px,144px);
left:-144px;
top:0px;
}

Output of Example 1.1:

Google's icon

If this method doesn’t work on IE8, then you can use following code:

1
<img onload="this.style.clip='rect(0px,281px,135px,144px);'" src="..." />

We tried to show you that the simple method of clipping image with CSS. You will like this ;)

Bookmark and Share
Categories: CSS Tags: , , , ,
  1. No comments yet.
  1. No trackbacks yet.
eXTReMe Tracker