How to use Position Property In CSS
Set the position: absolute
;
along with different top
values for each box causes them to overlap vertically, creating a visual effect of the boxes collapsing over each other within the .container
.
Syntax
position: absolute;
z-index: 2;
Example: Illustration of div collapse over each other Using Position Property.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < link rel = "stylesheet" href = "style.css" > < title >Collapsing Divs</ title > </ head > < body > < h2 >w3wiki</ h2 > < h3 >The elements collapse over each other using position property </ h3 > < div class = "container" > < div class = "box box1" >Box 1</ div > < div class = "box box2" >Box 2</ div > < div class = "box box3" >Box 3</ div > </ div > </ body > </ html > |
CSS
/* style.css */ body { display : flex; justify- content : center ; align-items: center ; height : 100 vh; margin : 0 ; } .container { height : 30 vh; } .box { width : 100px ; height : 100px ; background-color : rgb ( 40 , 187 , 35 ); border : 1px solid #333 ; position : absolute ; } .box 1 { top : 20px ; background : #29d84f ; } .box 2 { top : 40px ; background : #cf8f0f ; } .box 3 { top : 60px ; background : #e25909 ; } |
Output:
How to make div Collapse Over Each Other ?
The CSS position Property facilitates adding the effect of making divs collapse over each other, along with the z-index property. The z-index property determines the stack order of positioned elements, and elements with a higher z-index value will be stacked above those with lower values.
Table of Content
- Position Property
- Position and Z-index Properties