Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Định vị Relative (tương đối) trong CSS

Chúng ta có thể định nghĩa định vị của một phần tử trong CSS là relative - hiển thị phần tử bình thường (theo normal flow). Các phần tử với phương pháp định vị relative được định vị bởi các thuộc tính CSS Positioning (left, right, top, bottom).

Ví dụ 1: Relative positioning cơ bản

<!DOCTYPE html>
<html>
<head>
<style>
  p { margin: 0; }
  div:first-child {
    position: relative;
    top: 20px;
    background-color: orange;
    text-align: center;
  }
</style>
</head>
<body>
  <div>PostgreSQL</div>
  <p>PostgreSQL is a powerful, open source object-relational database system. It has more than 15 years of active development.................</p>
  <div></div>
</body>
</html>

Kết quả

Định vị Relative (tương đối) trong CSS

Ví dụ 2: So sánh Relative, Absolute, Fixed

<!DOCTYPE html>
<html>
<head>
<style>
  div { border: 2px double #a43356; margin: 5px; padding: 5px; }
  #d1 { position: relative; height: 10em; }
  #d2 { position: absolute; width: 20%; bottom: 10px; /*relative to parent d1*/ }
  #d3 { position: fixed; width: 30%; top: 10em; /*relative to viewport*/ }
</style>
</head>
<body>
  <div id="d1">
    PhoneGap is a software development framework by Adobe System, which is used to develop mobile applications. To develop apps using PhoneGap, the developer does not require to have knowledge of mobile programming language but only web-development languages like, HTML, CSS, and JScript.
    <mark>relative</mark>
    <div id="d2"><mark>absolute</mark></div>
    <div id="d3"><mark>fixed</mark></div>
  </div>
</body>
</html>

Kết quả

Định vị Relative (tương đối) trong CSS

Đặc điểm của position: relative:

  • Phần tử VẪN ở vị trí gốc trong normal flow
  • Có thể dịch chuyển bằng top, right, bottom, left
  • Không gian gốc VẪN được giữ lại (khác với absolute)
  • Tạo stacking context mới (cho z-index)
  • Làm mốc tham chiếu cho các phần tử con position: absolute

Use cases phổ biến:

  • Điều chỉnh nhỏ vị trí (nudge) mà không phá vỡ layout
  • Làm container cho absolute positioning
  • Tạo hiệu ứng parallax, animation
  • Z-index stacking context