본문으로 건너뛰기

Positioning Among Multiple HTML Elements

Positioning Using z-index

You can specify the position of HTML elements using the z-index property, which determines the stacking order of elements. The z-index property will be covered in more detail in later lessons.

z-index and Stacking

  • z-index defines the "stack level" of HTML elements. The higher the z-index number, the higher the element will be stacked.

    CSS
    .box1 {
    position: absolute;
    z-index: 1;
    }
    .box2 {
    position: absolute;
    z-index: 2;
    }
  • If two boxes overlap, the box with the higher z-index will be displayed on top. If the numbers are the same, the element that comes later in the code will be positioned above.

  • Here, box2 with a z-index of 2 will be positioned on top of box1 which has a z-index of 1.


Using absolute and relative

HTML
<div class="container">
<div class="small-box">Small Box</div>
</div>
CSS
.container {
position: relative;
}

.small-box {
position: absolute;
top: 10px;
left: 20px;
}

This CSS code sets the .small-box to an absolute position within the div using .container.

The .small-box is placed 20px to the right and 10px down from the top left corner of .container.


Follow the asterisk-highlighted part of the code to try inputting it.