11

I'm working with a CMS that allows only text in a certain div (HTML , like <br>, is parsed to &lt;br&gt;). It is fine with Unicode / HTML codes (e.g. &amp; would generate & and &#x00040; would generate @) but it will seemingly not allow a new line / carriage return. How can I put a <br> in the div, without using HTML?

I've tried:

Here is a fiddle with the same issue (and HTML structure as output by CMS) > https://jsfiddle.net/w3p4wgcc/ ...Is it just not possible?

Community
  • 1
  • 1
tymothytym
  • 1,571
  • 3
  • 16
  • 25

2 Answers2

27

With inline css i've managed to do the following:

<div style="white-space: pre-wrap;">
This is some new text,&#10;this text should be on a new line.
</div>

https://jsfiddle.net/6mqgrym9/

If you need all of your divs to be like this one could say in your stylesheet the following:

div {
    white-space: pre-wrap;
}

if these divs are contained in a root div (which has a id) one could do the following:

#idhere > div {
    white-space: pre-wrap;
}

If you're allowed to use some javascript you can try this:

<div>
    <script>
        document.currentScript.parentNode.innerHTML = 'This is some new text<br>this text should be on a new line.';
    </script>
</div>
Baklap4
  • 3,914
  • 2
  • 29
  • 56
  • Unfortunately I can't edit the HTML in that way, but it might be possible to create a global class of some sort... – tymothytym Jun 14 '16 at 12:16
  • global class? a css class you mean? if you are able to that'd be even a more beautiful solution.. yet you still need to be able to add the class to the `div` element – Baklap4 Jun 14 '16 at 12:19
  • Sorry, yes. A css class to the global stylesheet. The issue would be that I can't target divs individually with any great accuracy so I'd be mildly concerned that a change at a high level would have unseen (and undesirable) changes in other places. – tymothytym Jun 14 '16 at 12:21
  • Do these div's have anything uniques? Which seperates them from the other divs? – Baklap4 Jun 14 '16 at 12:23
  • @tymothytym if this answer helped you out please set it as an sollution – Baklap4 Jun 14 '16 at 13:13
  • Whilst it is helpful (I did up-vote), it unfortunately doesn't solve my original problem as I can't target the div with the css with a good enough accuracy. – tymothytym Jun 14 '16 at 13:19
  • the `\n` tags also are working after adding `pre-wrap`. thanks – Prometheus Feb 24 '20 at 23:52
5

You could also use the following in CSS.

div {
    white-space: pre-line;
}

The difference between pre-line, pre-wrap and pre is available under this link

Fabi0
  • 131
  • 2
  • 5