26

Look this very simple code

<!DOCTYPE html>
<html>
<head>
<style>
p::before {
    content: "Before - ";
}
</style>
</head>
<body>
<p>Hello</p>
<p>Bye</p>   
</body>
</html>

Css adds ¨Before -" at the start of every <P> and renders like this

enter image description here

If you use your mouse to select the text (for copy paste) you can select the original text, but not the Before or Aftter text added by css.

enter image description here

I have a very specific requirement where I need to allow users to select with the mosue the Before text. How would you do it?

Ricardo Polo Jaramillo
  • 12,110
  • 13
  • 58
  • 83
  • No you can't. That's what the phrase "pseudo" means. – Leo Dec 10 '14 at 02:36
  • 1
    Asked and answered, more than once. See [Is it possible to select css generated content?](http://stackoverflow.com/questions/24385171/is-it-possible-to-select-css-generated-content) –  Dec 10 '14 at 03:37

3 Answers3

17

This cannot be done within an HTML page, but as a hack, if you need to copy/paste pseudo elements, you can export the page to PDF and copy from it. In Chrome, for example, you can copy page's content from print preview.

Alex
  • 389
  • 3
  • 5
11

You can't, the before and after pseudo classes are not meant to be used for that purpose.

Eyal
  • 758
  • 6
  • 23
4

If users need to select the generated text, it should be considered content (and in the HTML), not presentation (and hidden in the CSS).

Don't use ::before or ::after, use HTML.

You could use JavaScript to insert it (if that would help):

var text = document.createTextNode('Before - ');
Array.prototype.forEach.call(document.getElementsByTagName('p'), function (p) {
    p.insertBefore(text.cloneNode(), p.firstChild);
});

This way the text itself is present in the DOM, unlike generated content from CSS.

David Thomas
  • 249,100
  • 51
  • 377
  • 410