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

Pseudo-element ::first-line trong CSS

Pseudo-element ::first-line trong CSS dùng để chọn dòng đầu tiên của nội dung bên trong một phần tử. Tuy nhiên, độ dài của dòng này có thể thay đổi tùy theo kích thước cửa sổ trình duyệt nếu chiều rộng của vùng chứa văn bản không được cố định.

Ví dụ cơ bản

Dưới đây là ví dụ minh họa cách sử dụng pseudo-element ::first-line:

<!DOCTYPE html>
<html>
<head>
<style>
  p::first-line {
    background-color: lightgreen;
    color: white;
  }
</style>
</head>
<body>
  <h2>Lorem Ipsum</h2>
  <p>Phasellus id ante turpis. Vestibulum luctus justo id odio iaculis condimentum. Vestibulum sapien mauris, feugiat id posuere vitae, condimentum blandit sapien.</p>
  <div id="divDisplay"></div>
  <script>
    divDisplay.textContent = 'Current window width: ' + window.innerWidth + 'px';
    window.addEventListener('resize', function() {
      divDisplay.textContent = 'Current window width: ' + window.innerWidth + 'px';
    });
  </script>
</body>
</html>

Kết quả

Khi chiều rộng cửa sổ ban đầu là 606px:

Pseudo-element ::first-line trong CSS

Khi tăng chiều rộng cửa sổ:

Pseudo-element ::first-line trong CSS

Khi chiều rộng phần tử chứa văn bản được cố định và resize cửa sổ:

Pseudo-element ::first-line trong CSS

Ví dụ với container có chiều rộng cố định

<!DOCTYPE html>
<html>
<head>
<style>
  p::first-line {
    background-color: #FF8A00;
    color: white;
  }
  div {
    width: 420px;
  }
</style>
</head>
<body>
  <div>
    <h2>Demo Heading</h2>
    <p>This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text.</p>
    <p>This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text.</p>
  </div>
</body>
</html>

Kết quả

Pseudo-element ::first-line trong CSS

Lưu ý quan trọng: Pseudo-element ::first-line chỉ áp dụng được cho các phần tử cấp khối (block-level elements). Các thuộc tính CSS được hỗ trợ bao gồm: font, color, background, word-spacing, letter-spacing, text-decoration, vertical-align, text-transform, line-height, và clear.