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

CSS Pseudo-element: Phần tử giả

Pseudo-element (Phần tử giả) trong CSS về cơ bản là một bộ chọn cho các phần cụ thể của một phần tử như ::first-letter, ::first-line, v.v. Pseudo-element ::after và ::before có thể dùng để chèn nội dung sau và trước một phần tử tương ứng.

Cú pháp

selector::pseudo-element {
    css-property: /* value */;
}

Lưu ý: CSS3 dùng hai dấu hai chấm :: để phân biệt với pseudo-class (một dấu :), tuy trình duyệt vẫn hỗ trợ : cho các pseudo-element cũ để tương thích ngược.

Các pseudo-element phổ biến

Pseudo-elementMô tả
::beforeChèn nội dung trước nội dung phần tử
::afterChèn nội dung sau nội dung phần tử
::first-letterChọn chữ cái đầu tiên
::first-lineChọn dòng đầu tiên
::selectionPhần được người dùng bôi chọn
::placeholderText placeholder của input
::markerBullet/số thứ tự của list item

Ví dụ 1: Tự động đánh số với counter

<!DOCTYPE html>
<html>
<head>
<style>
ol, ul { list-style: none; counter-reset: demo_var2; }
ul { counter-reset: demo_var1; }
ol > li::before {
    counter-increment: demo_var2;
    content: counter(demo_var2, lower-roman) ") ";
}
li::after {
    counter-increment: demo_var1;
    content: " " counter(demo_var1) ". ";
}
</style>
</head>
<body>
<ul>
    <li>Demo Line</li>
    <ol>
        <li>demo line</li>
        <li>demo line</li>
    </ol>
    <li>Demo Line</li>
    <ol>
        <li>demo line</li>
        <li>demo line</li>
    </ol>
    <li>Demo Line</li>
</ul>
</body>
</html>

Ví dụ 2: Style placeholder

<!DOCTYPE html>
<html>
<head>
<style>
::-webkit-input-placeholder { /* Chrome, Safari, Edge */
    color: blue;
    font-style: italic;
}
:-ms-input-placeholder { /* IE 10-11 */
    color: blue;
    font-style: italic;
}
::placeholder { /* Standard */
    color: blue;
    font-style: italic;
}
</style>
</head>
<body>
<h2>Sample Form</h2>
<textarea id="desc" name="desc" rows="5" cols="33" placeholder="Type here"></textarea>
<br />
<input type="text" name="author" placeholder="author name">
</body>
</html>

Ví dụ 3: Tooltip với ::before/::after

.tooltip {
    position: relative;
}
.tooltip::before {
    content: attr(data-tooltip);
    position: absolute;
    bottom: 100%;
    left: 50%;
    transform: translateX(-50%);
    background: #333;
    color: white;
    padding: 4px 8px;
    border-radius: 4px;
    white-space: nowrap;
    opacity: 0;
    pointer-events: none;
    transition: opacity 0.2s;
}
.tooltip:hover::before { opacity: 1; }

Lưu ý

  • Pseudo-element không tồn tại trong DOM, không thể chọn bằng JavaScript trực tiếp
  • ::before/::after bắt buộc có content (có thể rỗng: content: "")
  • Chỉ một ::before và một ::after cho mỗi phần tử