Thuộc tính vị trí CSS
Thí dụ
Định vị phần tử <h2>:
h2
{
position: absolute;
left: 100px;
top: 150px;
}
Thêm các ví dụ "Hãy tự mình thử" bên dưới.
Định nghĩa và Cách sử dụng
Thuộc position
tính chỉ định loại phương pháp định vị được sử dụng cho một phần tử (tĩnh, tương đối, tuyệt đối, cố định hoặc cố định).
Giá trị mặc định: | tĩnh |
---|---|
Thừa hưởng: | không |
Hoạt hình: | không. Đọc về hoạt hình |
Phiên bản: | CSS2 |
Cú pháp JavaScript: | đối tượng .style.position = "tuyệt đối" |
Hỗ trợ trình duyệt
Các số trong bảng chỉ định phiên bản trình duyệt đầu tiên hỗ trợ đầy đủ thuộc tính.
Property | |||||
---|---|---|---|---|---|
position | 1.0 | 7.0 | 1.0 | 1.0 | 4.0 |
Lưu ý: Giá sticky
trị này không được hỗ trợ trong Internet Explorer hoặc Edge 15 và các phiên bản cũ hơn.
Cú pháp CSS
position: static|absolute|fixed|relative|sticky|initial|inherit;
Giá trị tài sản
Value | Description | Play it |
---|---|---|
static | Default value. Elements render in order, as they appear in the document flow | |
absolute | The element is positioned relative to its first positioned (not static) ancestor element | |
fixed | The element is positioned relative to the browser window | |
relative | The element is positioned relative to its normal position, so "left:20px" adds 20 pixels to the element's LEFT position | |
sticky | The element is positioned based on the user's scroll position
A sticky element toggles between |
|
initial | Sets this property to its default value. Read about initial | |
inherit | Inherits this property from its parent element. Read about inherit |
Các ví dụ khác
Thí dụ
Cách định vị một phần tử so với vị trí bình thường của nó:
h2.pos_left {
position: relative;
left: -20px;
}
h2.pos_right {
position: relative;
left: 20px;
}
Thí dụ
Thêm định vị:
#parent1 {
position: static;
border: 1px solid blue;
width: 300px;
height: 100px;
}
#child1 {
position:
absolute;
border: 1px solid red;
top: 70px;
right: 15px;
}
#parent2 {
position: relative;
border: 1px solid blue;
width: 300px;
height: 100px;
}
#child2 {
position: absolute;
border: 1px solid red;
top: 70px;
right: 15px;
}
Các trang liên quan
Hướng dẫn CSS: Định vị CSS
Tham chiếu DOM HTML: thuộc tính vị trí