Home > Web Front-end > CSS Tutorial > How Can I Style Specific Lines of Text Beyond the `:first-line` Pseudo-element?

How Can I Style Specific Lines of Text Beyond the `:first-line` Pseudo-element?

DDD
Release: 2024-11-28 09:31:10
Original
771 people have browsed it

How Can I Style Specific Lines of Text Beyond the `:first-line` Pseudo-element?

Line Selection and Styling: Beyond First Lines with CSS and JS

Selecting specific lines of text for styling is a task that extends beyond the limitations of the CSS pseudo-element :first-line. While CSS alone may not suffice, JavaScript offers viable solutions.

JavaScript Approach

Using JavaScript, it is possible to wrap each word in a span element and dynamically assign a class based on its position in the paragraph. This approach:

  1. Splits the paragraph text into individual words.
  2. Wraps each word in a span element and appends it back to the paragraph.
  3. Listens for window resize events.
  4. Iterates through the spans, determining their position (line number) based on their offset top.
  5. Assigns line classes to the spans (e.g., line1, line2) to facilitate styling.

This method enables line selection and styling by applying classes to the corresponding spans, simplifying the process of highlighting every even or odd row.

Implementation Details

$(function(){ 
  var p = $('p'); 
  var words = p.text().split(' '); 
  var text = ''; 
  $.each(words, function(i, w){
                   if($.trim(w)) text = text + '<span>' + w + '</span> ' }
        ); //each word 
  p.html(text); 
  $(window).resize(function(){ 

    var line = 0; 
    var prevTop = -15; 
    $('span', p).each(function(){ 
      var word = $(this); 
      var top = word.offset().top; 
      if(top!=prevTop){ 
        prevTop=top; 
        line++; 
      } 
      word.attr('class', 'line' + line); 
    });//each 

  });//resize 

  $(window).resize(); //first one
});
Copy after login

Edge Cases

This approach assumes that the line classes do not significantly alter the size or width of the words, as it may impact the accuracy of the line numbering.

The above is the detailed content of How Can I Style Specific Lines of Text Beyond the `:first-line` Pseudo-element?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template