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

Xóa viền outline trên phần tử contenteditable với CSS

Khi phần tử có contenteditable="true", trình duyệt hiển thị viền outline khi focus. Để xóa, dùng outline: none.

Ví dụ mã nguồn

<!DOCTYPE html>
<html>
<head>
<style>
  body{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
  p{ font-size: 40px; }
  [contenteditable] {
    outline: none; /* Xóa outline mặc định */
    /* Tùy chọn: thêm style focus tùy chỉnh */
    /* outline: 2px solid #007bff; outline-offset: 2px; */
  }
</style>
</head>
<body>
<h1>Xóa viền Contenteditable</h1>
<p contenteditable="true">Đoạn văn này có thể chỉnh sửa. Thử click vào xem.</p>
</body>
</html>

Giải thích

  • [contenteditable] - Attribute selector chọn tất cả phần tử có attribute này
  • outline: none - Xóa viền focus mặc định của trình duyệt
  • outline: 0px solid transparent - Cách viết trong ví dụ gốc, tương đương

Cảnh báo về Accessibility (A11y)

Không nên xóa outline hoàn toàn nếu không cung cấp thay thế, vì người dùng bàn phím (Tab navigation) sẽ không biết đang focus ở đâu.

Cách đúng (Accessible)

[contenteditable] {
  outline: none; /* Xóa mặc định */
}
[contenteditable]:focus {
  /* Thay thế bằng style tùy chỉnh rõ ràng */
  box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.4);
  border-radius: 4px;
}

Hoặc dùng :focus-visible (hiện đại) để chỉ hiển thị focus khi dùng bàn phím:

[contenteditable]:focus-visible {
  outline: 2px solid #007bff;
  outline-offset: 2px;
}