Jsilvermist Jsilvermist - 7 months ago 9
HTML Question

Add content to the beginning of every line, like ::before does for the first line

I am trying to style my

<code>/<pre>
tags without preventing the user from being able to highlight and copy the code properly.

The way I was hoping to do this (see below) only works for the first line, and won't ever repeat.

I'm sure this could be made to work using JavaScript, but I'm not sure what the best way to do that without a large amount of processing would be.



body {
font-family: sans-serif;
}

code, pre {
background: #e5f3ff;
}

code.styled,
pre.styled {
display: block;
padding: 8px;
margin: 8px 0;
overflow-x: auto;
}

code.styled::before,
pre.styled::before {
content: "–";
padding-right: 8px;
}

<p>This is an example of using <code>::before</code> to add content,<br>
and still being able to highlight/copy text without copying prefix.</p>
<pre class="styled">
adb wait-for-device
adb reboot-bootloader
fastboot devices
</pre>
<p>Note: You can copy the code without having to worry about the prefix.</p>





What is the best way that I could achieve a similar effect, but spanning every line?

Answer

Here is a pure javascript solution

var _pre = document.querySelector("pre.styled");
_pre.innerHTML="<span class='line'>"+(_pre.textContent.split("\n").filter(Boolean).join("</span>\n<span class='line'>"))+"</span>";
body {
  font-family: sans-serif;
}

code, pre {
  background: #e5f3ff;
}

code.styled,
pre.styled {
  display: block;
  padding: 8px;
  margin: 8px 0;
  overflow-x: auto;
}

code.styled .line::before,
pre.styled .line::before {
  content: "–";
  padding-right: 8px;
}
<p>This is an example of using <code>::before</code> to add content,<br>
and still being able to highlight/copy text without copying prefix.</p>
<pre class="styled">
adb wait-for-device
adb reboot-bootloader
fastboot devices
</pre>
<p>Note: You can copy the code without having to worry about the prefix.</p>

Comments