Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight first character of every line using css or JS

I have requirement to highlight first character in each and every line, as example image below, all the content is in single paragraph, based on resolution change also it should behave same,

enter image description here

I have tried with flex box, and first child using script also, I could not able to find solution

Any help will be appreciated.

like image 512
Naveen Setty Avatar asked Dec 07 '22 17:12

Naveen Setty


2 Answers

Try this:

p::first-letter {
  font-weight: bold;
  color: #8A2BE2;
}
<p>Hi there</p>
<p>Color first!</p>

EDIT: Ok, since you need this per each line in one paragrpah, you'll have to this with a script.

var allLines = document.querySelector("p").innerHTML.split("\n");
allLines = allLines.filter(function(x){return x !== ""}).map(function(x){
return "<span>" + x.charAt(0) + "</span>" + x.substr(1);
}).join("<br/>");
document.querySelector("p").innerHTML = allLines;
span {
  color: red;
}
<p>
TEXT
SOME MORE TEXT
</p>
like image 171
Sveta Avatar answered Dec 10 '22 11:12

Sveta


CSS only responsive solution that uses mix-blend-mode, which is not supported by IE and Edge.

The idea is to use a colored overlay with a fixed width (the largest letter width) and mix-blend-mode: screen; to color only the 1st letter of each line.

You need to use a monospace font, so the color won't spill to the next letter if the 1st letter is narrow.

p {
  position: relative;
  font-family: monospace; /** to have constant character width **/
  font-size: 28px;
  background: white;
}

p::before {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  z-index: 1;
  background: red;
  mix-blend-mode: screen;
  pointer-events: none; /** to enable selected of the text under the pseudo element **/
  color: transparent; /** to hide the character **/
  content: 'W'; /** a character in your font to use as width **/
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis quis euismod orci. Morbi ullamcorper augue ipsum, at consectetur turpis dictum sed. Phasellus bibendum tellus eu aliquet congue. Morbi ultrices aliquam purus, id semper diam aliquet eget. Nulla
  at tellus lacus. Curabitur massa lectus, auctor et lobortis vel, sodales non diam. Pellentesque gravida tortor ac ex porta congue. Ut vestibulum arcu ex, ac lacinia tortor pulvinar id. Nulla sagittis, lectus at luctus dignissim, orci nulla interdum
  ex, at euismod nibh ipsum et lacus. Suspendisse potenti. Quisque ac eros nunc. Suspendisse sit amet dolor diam. Phasellus blandit commodo mi, at aliquam mi facilisis ut. Vestibulum lacinia enim tempor nunc elementum suscipit. Praesent ligula ipsum,
  venenatis et tellus at, imperdiet tempus lectus. Pellentesque consequat magna augue, at vestibulum sem facilisis nec.</p>
like image 28
Ori Drori Avatar answered Dec 10 '22 12:12

Ori Drori