Clip: Cropping an image

The clip property applies an offset on a displayed image, allowing to hide a part.

In combination with other CSS Properties (top, left, overflow), it can create thumbnails or crop images, or any other element.
When the visitor clicks on the thumbnail, the image is displayed instantly as already present in memory.

Syntax of clip

It has two possible values:

Auto: no clipping.

rect (top right bottom left): defines the offsets to be applied to the image. You can omit a value by replacing it by auto (which therefore works at two levels), in this case there is no offset to that side.

The demonstration will allow to test visually different values.

Important

Clip apply only if the tag or the container position is absolute.

The overflow property of the outer container must be set to hidden. Thus the image is swaging to the container size and the clip property can crop the content.

Clip products margins around the image. To remove them, gives the tag or the image a top and left properties corresponding to negative values of top and left of the clip property.

Example of code

<style>
img
{
  position:absolute;
  clip:rect(0, 0, 10px, 20px);
}
</style

JavaScript

Clip is changed dynamically with this command, which cuts a margin of 10 pixels:

element.style.clip="rect(10px, auto, auto, 10px)";

And to crop the image by removing the margins:

element.style.clip="rect(10px, auto, auto, 10px)";
element.style.top="-10px"; element.style.left="-10px";

Ideally, the element is to be cropped in an outer container:

.clipzone
{
  position:relative;
  width:100px; 
  height:100px;
  overflow:hidden;
}

.clipped
{
  position:absolute;
}
<div class="clipzone">
  <img class="clipped" id="image1" src="" />
</div>

This container is integrated in the flow of the contents of the page with the relative position and allows the content to have the absolute position.
The property overflow: hidden avoids exceeding the limits of the container. (The scroll value would have the same effect.)

To access the image, it is assigned an identifier, in this case image1. Finally, the complete JavaScript code is as follows:

var i = document.getElementById("image1");
i.style.clip="rect(10x, auto, auto, 10px)";
i.style.top="-10px";
i.style.left="-10px"; 

Reference: CSS 2.0 Specification Visual Effects.

CSS 3

The clip property has not been changed in CSS 3.

Demonstration of clipping an image

The clip property can be applied to any tag. This demo shows how to crop an image in a container, a <div>.
For the margins to be removed, positions y and x must be the negative of the top and left values.

Top Right Bottom Left Position Y Position X


© 2010-2012 Xul.fr