How to make div Collapse Over Each Other ?
Last Updated :
30 Jan, 2024
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.
Using Position Property
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 >GeeksforGeeks</ 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
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:
Using Position and Z-index Properties
The z-index
property is used to control the stacking order. Higher z-index
values bring elements to the front. In this case, box3
has the highest z-index
, so it appears on top of the other boxes.
Example: Illustration of div collapse over each other Using Position and Z-index Properties.
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 >
< 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
body {
display : flex;
justify- content : center ;
align-items: center ;
height : 100 vh;
margin : 0 ;
}
.box {
width : 100px ;
height : 100px ;
background-color : lightblue;
border : 1px solid #333 ;
position : absolute ;
}
.container {
height : 30 vh;
position : absolute ;
}
.box 1 {
z-index : 2 ;
background : #29d84f ;
}
.box 2 {
z-index : 1 ;
top : 30px ;
left : 30px ;
background : #cf8f0f ;
}
.box 3 {
z-index : 3 ;
top : 60px ;
left : 60px ;
background : #e25909 ;
}
|
Output:
Share your thoughts in the comments
Please Login to comment...