Để định vị các phần tử, CSS cung cấp các phương thức định vị sau:
1. Định vị tương đối (Relative Positioning)
Với định vị tương đối, phần tử được định vị so với vị trí bình thường của nó. Sử dụng position: relative.
Ví dụ
<!DOCTYPE html>
<html>
<head>
<style>
div.demo {
position: relative;
color: white;
background-color: orange;
border: 2px dashed blue;
left: 50px;
}
</style>
</head>
<body>
<h2>Tiêu đề Demo</h2>
<p>Đây là văn bản demo.</p>
<p>Đây là văn bản demo.</p>
<div class="demo">position: relative;</div>
<p>Đây là văn bản demo khác.</p>
</body>
</html>
Kết quả

2. Định vị tuyệt đối (Absolute Positioning)
Với định vị tuyệt đối, một phần tử được định vị so với tổ tiên được định vị gần nhất.
Ví dụ
<!DOCTYPE html>
<html>
<head>
<style>
div.demo1 {
position: relative;
color: white;
background-color: orange;
border: 2px dashed blue;
width: 600px;
height: 200px;
}
div.demo2 {
position: absolute;
color: white;
background-color: orange;
border: 2px dashed blue;
top: 50px;
right: 0;
width: 300px;
height: 100px;
}
</style>
</head>
<body>
<h2>Tiêu đề Demo</h2>
<p>Đây là văn bản demo.</p>
<p>Đây là văn bản demo.</p>
<p>Đây là văn bản demo.</p>
<p>Đây là văn bản demo.</p>
<div class="demo1">
position: relative;
<div class="demo2">position: absolute;</div>
</div>
<p>Đây là văn bản demo khác.</p>
<p>Đây là văn bản demo.</p>
<p>Đây là văn bản demo.</p>
</body>
</html>
Kết quả

3. Định vị cố định (Fixed Positioning)
Phần tử được đặt với position: fixed; sẽ giữ nguyên vị trí ngay cả khi trang được cuộn.
Ví dụ
<!DOCTYPE html>
<html>
<head>
<style>
div.demo1 {
position: relative;
color: white;
background-color: orange;
border: 2px dashed blue;
width: 600px;
height: 200px;
}
div.demo2 {
position: absolute;
color: white;
background-color: orange;
border: 2px dashed blue;
top: 50px;
right: 0;
width: 300px;
height: 100px;
}
div.demo3 {
position: fixed;
bottom: 0;
right: 20px;
width: 500px;
border: 3px solid orange;
color: blue;
}
</style>
</head>
<body>
<h2>Tiêu đề Demo</h2>
<p>Đây là văn bản demo.</p>
<p>Đây là văn bản demo.</p>
<p>Đây là văn bản demo.</p>
<p>Đây là văn bản demo.</p>
<div class="demo1">
position: relative;
<div class="demo2">position: absolute;</div>
<div class="demo3">position: fixed;</div>
</div>
<p>Đây là văn bản demo khác.</p>
</body>
</html>
Kết quả

Tóm tắt:
| Loại | Mô tả |
|---|---|
| static | Mặc định, không bị ảnh hưởng bởi top/bottom/left/right |
| relative | Định vị so với vị trí bình thường |
| absolute | Định vị so với tổ tiên được định vị gần nhất |
| fixed | Định vị so với viewport, cố định khi cuộn |