How z-index works in CSS ?
Last Updated :
17 Mar, 2021
In this article we are going to see how z-index works in CSS. Z-index works as a stack for the elements that are visible on the screen. We can assign number to z-index property to assign it a position in stack. Assigned number can be negative. Greater number assigns front position and lesser number assigns behind position. Consider example that an img tag has z-index as 1 and another h1 tag has z-index as 2. So tag with z-index equal to 2 will appear before z-index equal to 1, i.e. h1 tag content will appear stacked on img tag. Default z-index is 0 for all elements.
Syntax:
z-index: number;
Approach: In this example we will use an image tag and header tag to stack on each other. We will assign z-index to image tag.
Example 1: In below code we try to stack h1 header on image by assigning image tag a z-index of -1.
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< style >
#image1{
height: 100px;
width: 100px;
z-index: -1;
position: absolute;
}
</ style >
</ head >
< body >
< h1 >z-index property in css</ h1 >
< div id = "image1" ></ div >
< img id = "image1" src =
alt = "" >
< p >Geeks for Geeks is the best website for CS.</ p >
</ body >
</ html >
|
Output:
Example 2: In below code we try to stack image on h1 header by assigning image tag a z-index of 1.
HTML
<!DOCTYPE html>
< html lang = "en" >
< style >
#image1{
height: 100px;
width: 100px;
z-index: 1;
position: absolute;
}
</ style >
< body >
< h1 >z-index property in css</ h1 >
< div id = "image1" ></ div >
< img id = "image1" src =
alt = "" >
< p >Geeks for Geeks is the best website for CS.</ p >
</ body >
</ html >
|
Output:
Share your thoughts in the comments
Please Login to comment...