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

Thuộc tính CSS3 Outline Offset

Giới thiệu

Thuộc tính outline-offset tạo khoảng cách giữa outline (viền ngoài) và border (viền trong) của phần tử. Khác với border, outline:

  • Không chiếm diện tích layout (không ảnh hưởng box model)
  • Không thể bo tròn bằng border-radius
  • Luôn là hình chữ nhật (trừ Firefox hỗ trợ outline-radius non-standard)
  • Có thể đặt vị trí bằng outline-offset (âm = đè lên border, dương = cách ra ngoài)

Cú pháp

outline-offset: <length>; /* px, em, rem... */

Ví dụ: Outline cách border 15px

<!DOCTYPE html>
<html>
<head>
  <style>
    .demo-box {
      margin: 20px;
      padding: 10px;
      width: 300px;
      height: 100px;
      border: 5px solid pink;        /* Viền trong */
      outline: 5px solid green;      /* Viền ngoài */
      outline-offset: 15px;          /* Cách border 15px */
    }
  </style>
</head>
<body>
  <div class="demo-box">TutorialsPoint</div>
</body>
</html>

Các trường hợp sử dụng

Giá trịHiệu ứngUse case
outline-offset: 0Outline sát border (mặc định)Focus ring chuẩn
outline-offset: 4pxOutline cách ra 4pxFocus ring rõ ràng, accessible
outline-offset: -2pxOutline đè lên border (nằm trong)Hiệu ứng đặc biệt, debug
outline-offset: 2px + outline: 2px dashedViền chấm cách đềuSelected state, drag target

Accessibility: Focus Visible

/* Focus ring đẹp, accessible */
:focus-visible {
  outline: 3px solid #3498db;
  outline-offset: 2px;
  border-radius: 4px; /* Không tác động lên outline, nhưng hint cho dev */
}

/* Tùy chỉnh cho từng component */
.btn:focus-visible {
  outline: 2px solid currentColor;
  outline-offset: 3px;
}

.input:focus-visible {
  outline: 2px solid #3498db;
  outline-offset: 2px;
}

Lưu ý

  • outline-offset không hoạt động nếu không có outline (khác none)
  • Không thể animate outline-offset trực tiếp (dùng box-shadow thay thế nếu cần animation)
  • Khác với box-shadow: outline không bị clip bởi overflow: hidden hoặc border-radius
  • IE/Edge cũ không hỗ trợ outline-offset — dùng box-shadow: 0 0 0 3px color làm fallback