How to display a label having text with line breaks?
There is no way of adding HTML tags in a <textarea>
tag, so formatting with css for example or using <br>
tags is not going to work.
Now, <textarea rows="4" cols="20">
, is let's say the best you can do: you define the minimum rows to be show as "4" and the minimum amount of characters per row: "20".
The best method though is using <div contenteditable="true"></div>
in which you can use tags like <br>
and also css styling.
Give the label white-space: pre-wrap
and it will break line as the text area does
textarea {
height: 70px;
}
label {
white-space: pre-wrap;
}
<textarea>
First day
1-one apple.
2-one orange.
3-two cups of milk.
</textarea>
<br><br>
<label>
First day
1-one apple.
2-one orange.
3-two cups of milk.
</label>
Besides the white-space
property combined with a new line character (e.g. \n
), the HTML way to break line is using <br>
, add here is a small sample how they work and differ.
Note, even space's are preserved using e.g. white-space: pre
, as seen in the "inline" code sample
var sample_script = document.querySelector('.sample.script');
var name = "One Two Three";
var name1 = name.replace(/ /g, '\n');
var name2 = name.replace(/ /g, '<br>');
sample_script.innerHTML += name1;
sample_script.innerHTML += "<br><br>";
sample_script.innerHTML += name2;
div.pre {
white-space: pre;
}
/* styling for this demo */
body {display: flex;}
.sample {flex: 1; margin: 0 20px;}
<div class="sample inline">
Inline
<hr>
<div>
One
Two
Three
</div>
<div class="pre">
One
Two
Three
</div>
</div>
<div class="sample script">
Script
<hr>
</div>