Ví dụ về thuộc tính z-index

Thuộc tính z-index

Thuộc tính z-index thiết lập thứ tự xếp chồng nhau của một thành phần vị trí.

Thứ tự chồng nhau được sắp xếp dựa theo giá trị số, thành phần HTML nào có chỉ số z-index cao hơn sẽ nằm trên, ngược lại sẽ nằm dưới, giá trị mặc định là 0.

Có thể sử dụng số âm.
Giá trị tốt nhất là không sử dụng đơn vị.

Chú ý: z-index chỉ làm việc cùng với thuộc tính position.

z-index 2 thành phần

<html>
<head>
<style type="text/css">
div {
    position: relative;
}

div p.exZIndex02 {
    position: absolute;
    top: 50px;
    left: 50px;
}
</style>
</head>

<body>
<div>
<p class="exZIndex01"><img src="img_num01.gif" alt="1" /></p>
<p class="exZIndex02"><img src="img_num02.gif" alt="2" /></p>
</div>
</body>
</html>

1

2

Theo mặc định của trình duyệt, thành phần nào sử dụng position sẽ được sắp xếp nằm bên trên, tuy nhiên ta sẽ sử dụng thuộc tính z-index để sắp xếp lại trật tự theo ý muốn:

<style type="text/css">
div {
    position: relative;
}

div p.exZIndex01 {
    position: absolute;
    z-index: 10;
}

div p.exZIndex02 {
    position: absolute;
    top: 50px;
    left: 50px;
}
</style>

1

2

z-index 3 thành phần

<html>
<head>
<style type="text/css">
div {
    position: relative;
}

div p.exZIndex02 {
    position: absolute;
    top: 50px;
    left: 50px;
}

div p.exZIndex03 {
    position: absolute;
    top: 100px;
    left: 100px;
}
</style>
</head>

<body>
<div>
<p class="exZIndex01"><img src="img_num01.gif" alt="1" /></p>
<p class="exZIndex02"><img src="img_num02.gif" alt="2" /></p>
<p class="exZIndex03"><img src="img_num03.gif" alt="3" /></p>
</div>
</body>
</html>

1

2

3

Ta sử dụng z-index cho thành phần thứ hai:

<style type="text/css">
div {
    position: relative;
}

div p.exZIndex02 {
    position: absolute;
    top: 50px;
    left: 50px;
    z-index: 10;
}

div p.exZIndex03 {
    position: absolute;
    top: 100px;
    left: 100px;
}
</style>

1

2

3

Ta tiếp tục sử dụng z-index cho thành phần thứ nhất:

<style type="text/css">
div {
    position: relative;
}

div p.exZIndex01 {
    position: absolute;
    z-index: 20;
}

div p.exZIndex02 {
    position: absolute;
    top: 50px;
    left: 50px;
    z-index: 10;
}

div p.exZIndex03 {
    position: absolute;
    top: 100px;
    left: 100px;
}
</style>

1

2

3