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

Định vị Fixed (Cố định) trong CSS

Chúng ta có thể định nghĩa định vị của một phần tử trong CSS là fixed - hiển thị phần tử tương đối với viewport của người dùng (cửa sổ trình duyệt). Các phần tử với phương pháp định vị fixed không di chuyển ngay cả khi cuộn trang và được định vị bởi các thuộc tính CSS Positioning (left, right, top, bottom).

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

<!DOCTYPE html>
<html>
<head>
<style>
  p { margin: 0; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
  div:first-child { background-color: orange; text-align: center; }
  div:last-child { width: 250px; height: 100px; margin: auto; background-color: turquoise; position: absolute; z-index: -1; top: 0; left: 0; right: 0; bottom: 0; }
</style>
</head>
<body>
  <div>What is ASP.NET?</div>
  <p>ASP.NET is a web application framework developed and marketed by Microsoft to allow programmers to build dynamic web sites............</p>
  <div> </div>
</body>
</html>

Kết quả

Định vị Fixed (Cố định) 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">
    Android is an open source and Linux-based operating system for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies.
    <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ị Fixed (Cố định) trong CSS

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

  • Rời hoàn toàn khỏi normal document flow
  • Định vị tương đối với viewport (không phải parent)
  • Không bao giờ di chuyển khi scroll trang
  • Tạo stacking context mới
  • Không chịu ảnh hưởng bởi transform/opacity/filter của ancestor (trừ một số trường hợp)
  • In ấn: hiển thị trên mọi trang (mỗi trang in)

Use cases phổ biến:

  • Sticky header / navigation bar
  • Back to top button
  • Chat widget, support button
  • Cookie consent banner
  • Modal overlay (với backdrop fixed)
  • Loading spinner toàn màn hình

Lưu ý mobile: Trên iOS Safari, fixed elements có thể bị ẩn bởi address bar khi scroll. Giải pháp: position: sticky; top: 0 hoặc dùng viewport-fit=cover + CSS env() variables.