How to display a label having text with line breaks?

一世执手 提交于 2019-12-04 23:12:12

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>

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.

If you are fetching text from textarea itself then when we hit enter in textarea that creates new line return. You can replace that newline return with

/n, /r with <br>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!