Home > Web Front-end > CSS Tutorial > How Can I Target and Style Specific Lines of Text in CSS and JavaScript?

How Can I Target and Style Specific Lines of Text in CSS and JavaScript?

Patricia Arquette
Release: 2024-11-27 06:38:14
Original
329 people have browsed it

How Can I Target and Style Specific Lines of Text in CSS and JavaScript?

How to Target and Stylize Individual Lines of Text in CSS/JS

Selecting and styling specific lines of text may seem straightforward with CSS's :first-line pseudo-element, but what if you need to target any line within the text?

While pure CSS doesn't offer a way to select arbitrary lines, JavaScript can fill the gap.

A JavaScript Solution

One approach using JavaScript is to wrap each word in a span element and assign a unique class based on the span's position in the text. Here's the code:

$(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

This code essentially breaks the text into individual words, wraps them in spans with CSS classes, and assigns class names based on the span's line position as the browser window is resized.

Applications

To highlight every even line of a paragraph, you can modify the code:

$('span.even, span.odd').css({
  'background-color' : '#ccc'
});
Copy after login

Caveats

It's important to note that edge cases, such as class name changes affecting word size or width, may impact the accuracy of the script.

The above is the detailed content of How Can I Target and Style Specific Lines of Text in CSS and JavaScript?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template