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

CSS Loại bỏ gạch chân mặc định của link

Mặc định, tất cả các liên kết (link) trong HTML đều được trang trí với gạch chân (underline). Chúng ta có thể loại bỏ gạch chân này bằng thuộc tính CSS text-decoration.

Cú pháp

selector {
    text-decoration: none | underline | overline | line-through | blink;
}

Ví dụ 1: Bỏ gạch chân, thêm italic

<!DOCTYPE html>
<html>
<head>
<style>
p { padding: 5px; box-shadow: inset 0 0 5px violet; }
a {
    font-style: italic;
    text-decoration: none;
}
</style>
</head>
<body>
<a href="#">Demo</a>
<p>
    <a href="https://example.com/">Example domain</a>
</p>
</body>
</html>

Ví dụ 2: Bỏ gạch chân, style link cuối khác

<!DOCTYPE html>
<html>
<head>
<style>
div {
    margin: auto; width: 50%;
    text-align: right; color: green;
    border: thin dashed red; padding: 1rem;
}
a { text-decoration: none; }
a:last-child {
    color: inherit;
    background-color: moccasin;
    padding: 0.25em 0.5em;
    border-radius: 4px;
}
</style>
</head>
</body>
<body>
<div>
    <a href="#">Link Demo</a>
    <p> Watch this: <a href="https://example.com/">Example site</a> </p>
</div>
</body>
</html>

Modern: text-decoration shorthand

/* CSS Text Decoration Level 3 */
a {
    text-decoration: none;           /* Bỏ gạch chân */
    text-decoration-line: underline; /* Loại gạch: underline, overline, line-through */
    text-decoration-color: #0066cc;  /* Màu gạch */
    text-decoration-style: solid;    /* solid, double, dotted, dashed, wavy */
    text-decoration-thickness: 2px;  /* Độ dày */
    text-underline-offset: 4px;      /* Khoảng cách gạch - text */
}

/* Hover: đổi style gạch chân */
a:hover {
    text-decoration: underline wavy #e91e63 3px;
    text-underline-offset: 6px;
}

Accessibility: Không bỏ gạch chân nếu chỉ dùng màu phân biệt

/ * KHÔNG TỐT - Chỉ dùng màu */
a { color: blue; text-decoration: none; }
a:hover { color: darkblue; }

/ * TỐT - Có underline + màu */
a { color: blue; text-decoration: underline; text-underline-offset: 2px; }
a:hover { color: darkblue; text-decoration-style: wavy; }

/ * HOẶC - Dùng border-bottom tùy chỉnh */
a {
    color: blue;
    text-decoration: none;
    border-bottom: 1px solid currentColor;
    padding-bottom: 2px;
}

Lưu ý

  • text-decoration: none trên link có thể gây khó khăn cho người dùng nhận diện link
  • Luôn cung cấp ít nhất một chỉ báo visual khác màu sắc (underline, border, icon, background)
  • text-underline-offset và cho kiểm soát tốt hơn (hiện đại)