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

CSS position: absolute

Định vị tuyệt đối (absolute)

position: absolute lấy phần tử ra khỏi luồng tài liệu bình thường. Vị trí được xác định bởi top, right, bottom, left tương đối với **phần tử cha gần nhất có position khác static** (relative, absolute, fixed, sticky). Nếu không có, tính từ <html> (initial containing block).

Ví dụ minh họa

<!DOCTYPE html>
<html>
<head>
  <style>
    div.one {
      position: relative; /* Làm gốc tọa độ */
      width: 500px;
      height: 150px;
      border: 2px solid blue;
    }
    div.two {
      position: absolute;
      top: 70px;
      right: 0;
      width: 300px;
      height: 50px;
      border: 2px solid yellow;
      background: rgba(255,255,0,0.2);
    }
  </style>
</head>
<body>
  <h2>position: absolute;</h2>
  <p>Phần tử absolute định vị tương đối cha relative gần nhất.</p>
  <div class="one">
    Div cha: position: relative;
    <div class="two">Div con: position: absolute; top: 70px; right: 0</div>
  </div>
</body>
</html>

Div con (.two) định vị so với div cha (.one) nhờ cha có position: relative. Nếu cha không có position, con sẽ định vị so với trang.