The CSS clip
property defines a rectangular region through which an element’s content can be shown. Anything outside of this region will be hidden. It is typically used with absolutely positioned elements.
Note: The clip
property is now considered obsolete and is replaced by the clip-path
property, which offers more flexibility and is recommended for new projects. However, understanding clip
can still be useful for maintaining older codebases.
Syntax
clip: rect(top, right, bottom, left);
top
: The top edge of the rectangle.right
: The right edge of the rectangle.bottom
: The bottom edge of the rectangle.left
: The left edge of the rectangle.
Important: The clip
property only works with elements that have position: absolute;
or position: fixed;
.
Example
Here is a simple example demonstrating how the clip
property works:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS Clip Example</title> <style> .clip-example { position: absolute; width: 300px; height: 200px; background-color: lightblue; border: 2px solid darkblue; clip: rect(20px, 150px, 120px, 30px); /* Alternative using clip-path for modern use: clip-path: inset(20px 150px 80px 30px); */ } </style> </head> <body> <div class="clip-example"> This text is inside a clipped box. Only part of this text will be visible. </div> </body> </html>
Explanation
- HTML Structure:
.clip-example
: Thisdiv
is styled to be absolutely positioned and has a specificclip
property applied.
- CSS Styling:
position: absolute;
: Required for theclip
property to take effect.clip: rect(20px, 150px, 120px, 30px);
: This defines a rectangle that starts 20px from the top, 150px from the left (right edge), 120px from the top (bottom edge), and 30px from the left. Only the content within this rectangle will be visible.
Visualization
Imagine a box around the .clip-example
element. The clip
property defines a smaller, rectangular window through which only a portion of the element is displayed. Everything outside this rectangle is hidden.
Practical Use
- The
clip
property is useful for creating simple image cropping effects or revealing parts of an element. - Since
clip
is obsolete, usingclip-path
with properties likeinset()
is the modern approach, providing more options like rounded rectangles and paths.
Modern Replacement: clip-path
Here’s how you can achieve the same effect using clip-path
:
.clip-example { position: absolute; width: 300px; height: 200px; background-color: lightblue; border: 2px solid darkblue; clip-path: inset(20px 150px 80px 30px); }
clip-path
offers more flexibility, including shapes like circles and polygons, making it a better choice for modern web development.