How to Overlap Elements in CSS: Simple Guide with Examples
To overlap elements in CSS, use the
position property with values like relative, absolute, or fixed, and control stacking order with z-index. Elements with higher z-index values appear on top of those with lower values.Syntax
Use the position property to take elements out of normal flow or adjust their position, and z-index to control which element appears on top.
position: can bestatic(default),relative,absolute, orfixed.z-index: a number that sets stacking order; higher numbers are on top.
css
selector {
position: relative; /* or absolute, fixed */
z-index: number;
}Example
This example shows two colored boxes overlapping. The red box is positioned absolutely and placed on top using a higher z-index.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Overlap Example</title> <style> .container { position: relative; width: 200px; height: 150px; border: 1px solid #ccc; } .box1 { position: absolute; top: 20px; left: 20px; width: 100px; height: 100px; background-color: red; z-index: 2; } .box2 { position: absolute; top: 50px; left: 50px; width: 100px; height: 100px; background-color: blue; z-index: 1; } </style> </head> <body> <div class="container"> <div class="box1"></div> <div class="box2"></div> </div> </body> </html>
Output
A 200x150 pixel container with two overlapping squares: a red square on top left and a blue square partially behind it shifted down and right.
Common Pitfalls
Common mistakes when overlapping elements include:
- Not setting
positionto anything other thanstatic, soz-indexhas no effect. - Using the same
z-indexvalue, causing unpredictable stacking. - Forgetting that
z-indexonly works on positioned elements (relative,absolute,fixed).
css
/* Wrong: z-index ignored because position is static (default) */ .element { z-index: 10; /* position is missing */ } /* Right: position set so z-index works */ .element { position: relative; z-index: 10; }
Quick Reference
Tips for overlapping elements:
- Always set
positiontorelative,absolute, orfixedto usez-index. - Higher
z-indexmeans the element appears on top. absolutepositions relative to the nearest positioned ancestor.relativemoves element without removing it from flow.- Use
position: fixedto overlap relative to the viewport.
Key Takeaways
Use position (relative, absolute, fixed) with z-index to overlap elements.
z-index only works on positioned elements, not static ones.
Higher z-index values appear on top of lower ones.
Absolute positioning moves elements relative to nearest positioned ancestor.
Relative positioning shifts elements without removing them from layout flow.