demosthenes.info

I’m Dudley Storey, the author of Pro CSS3 Animation. This is my blog, where I talk about web design and development with , and . To receive more information, including news, updates, and tips, you should follow me on Twitter or add me on Google+.

web developer guide

my books

Book cover of Pro CSS3 AnimationPro CSS3 Animation, Apress, 2013

my projects

CSSslidy: an auto-generated #RWD image slider. 3.8K of JS, no JQuery. Drop in images, add a line of CSS. Done.

tipster.ioAutomatically provides local tipping customs and percentages for services anywhere.

Audrey Hepburn Eyes

CSS clip

css / properties

Estimated reading time: 1 minute, 43 seconds

clip has been a misunderstood and ignored property for a long time. That is beginning to change with the emergence of related CSS3 properties such as background-clip, but clip itself has been present in the spec since CSS 2.1.

clip is perhaps best understood as a “window” through which portions of content may be seen. While this window may be of any dimension, the visible clip area is always rectangular. clip is only applicable to elements that are positioned absolute.

You have likely witnessed clip in action without really seeing it: an absolutely positioned div with a too-small height and width applied and overflow:hidden applied will clip its content, but clip itself is more powerful than that.

Before we begin, it’s important to understand the order of coordinates for clip and what they mean.

CSS clip area diagramThe clip area is given as a series of numbers. These numbers are top, right, bottom and left offsets for the clip area from the top and left of the image. They are specified in the same order as the shortcuts for specifying all sides when setting margin and padding in the box model. If you have difficulty recalling the order, just remember the acronym TRBL, pronounced “trouble”.

So if we wanted to clip an absolutely positioned image like this to show just the eyes, we would work out the clipping area coordinates as offsets from the top and left of the picture:

And apply them to our CSS as follows:

img#audrey-hepburn { clip: rect(165px,564px,260px,218px); position: absolute; }

At this stage your objection might be “but why would I want to do that? if I only wanted to show a portion of an image, I’d use PhotoShop to crop the image down so I could only see that part. Otherwise, I am loading the entire image to only show a small area of it, which increases my page loading time.”

In most cases you would be totally correct. However, as you will see, clip is useful in all sorts of circumstances.

comments powered by Disqus

This site helps millions of visitors while remaining ad-free. For less than the price of a cup of coffee, you can help pay for bandwidth and server costs while encouraging further articles.