CSS Clip

The CSS clip property is one of the least understood CSS properties, andtherefore one of the least used.

For a start clip only works on absolutely positioned elements, so if you plan on using it you will need to make a mental note of this when thinking about page layout. It works by only showing a portion of the element it is applied to, based on the values supplied in the CSS declaration.

For example:

img {
position: absolute;
clip: rect(50px 200px 150px 100px);
}

NB* The W3C recommendation has commas in between the values, but it doesn’t work in IE (surely not!) if commas are used.

The declaration is in two parts: the shape and the values. The shape is always rect as that is the only one supported. The values are top, right, bottom and left - in the same order as margins and padding.  However, unlike margins and padding bottom is measured from the top, and right is measured from the left.

bike-trbl

Applying the style to the image would result in only the light square in the background showing.

One possible application of the clip property in modern browsers is the creation of thumbnails as can be seen in this demo.  It takes advantage of the fact that the default clip for any absolutely positioned element is ‘auto’, and restores this on hover like so:

img:hover {
clip: rect(auto, auto, auto, auto);
}

Using z-index, opacity and shadows it would be possible to extend the demo to a nice lightweight gallery, all based on the CSS clip property.

A rather more complex use of clip can be seen in this Sitepoint CSS quiz. See if you can figure it out without reading the answer!

Leave a Reply