Chapter 12: CSS Shapes & Figures
CSS is not just for boxes. With a few creative properties, you can draw complex geometric figures, create organic shapes, and even clip images into unique silhouettes. This chapter explores how to move beyond the rectangle to create a more dynamic visual language.
1. Circles and Ellipses with border-radius
The most common way to create shapes is by manipulating the corners of a box.
Basic Circle
.circle {
width: 100px;
height: 100px;
background: #2563eb;
border-radius: 50%; /* Half of the width/height creates a circle */
}
Basic Ellipsis
.ellipse {
width: 150px;
height: 80px;
background: #10b981;
border-radius: 50%; /* On a non-square box, 50% creates an ellipse */
}
2. Polygons and Custom Shapes with clip-path
clip-path is the most powerful tool for drawing. It defines a specific region of an element that should be visible, effectively "cutting out" the rest.
Common Polygons
/* Triangle */
.triangle {
clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
}
/* Diamond */
.diamond {
clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
}
/* Hexagon */
.hexagon {
clip-path: polygon(25% 0%, 75% 0%, 100% 50%, 75% 100%, 25% 100%, 0% 50%);
}
3. Organic Shapes with border-radius (Eight Values)
You can specify different radii for each corner, and even different horizontal and vertical radii for each corner using the slash / syntax.
.blob {
width: 200px;
height: 200px;
background: linear-gradient(135deg, #f472b6, #db2777);
border-radius: 60% 40% 30% 70% / 60% 30% 70% 40%;
}
This creates "blob" shapes that feel natural and organic, perfect for modern background decorations.
4. Drawing with ::before and ::after
Pseudo-elements allow you to add extra shapes to an element without adding more HTML tags. This is how many complex CSS icons and figures are built.
Example: A Speech Bubble
.speech-bubble {
position: relative;
background: #f1f5f9;
border-radius: 12px;
padding: 1rem;
}
.speech-bubble::after {
content: "";
position: absolute;
bottom: -15px;
left: 20px;
border-width: 15px 15px 0;
border-style: solid;
border-color: #f1f5f9 transparent;
}
5. CSS Patterns with Gradients
By repeating small shapes created with gradients, you can build complex patterns.
.polka-dot {
background-image: radial-gradient(#cbd5e1 20%, transparent 20%);
background-size: 20px 20px;
}
.stripes {
background: repeating-linear-gradient(
45deg,
#f8fafc,
#f8fafc 10px,
#f1f5f9 10px,
#f1f5f9 20px
);
}
6. Debugging Checklist
- Is the shape invisible? (Check
overflow: hiddenor incorrectclip-pathcoordinates). - Is the
clip-pathaffecting mouse clicks? (Only the visible area is clickable). - Do
border-radius: 50%shapes look like ovals? (Check ifwidthandheightare equal). - Is the pseudo-element missing? (Check if
content: ""anddisplayare set). - Are complex shapes slowing down performance? (Use
will-change: clip-pathsparingly).