如何显示带有换行符的文本标签?

2022-01-25 00:00:00 label line-breaks html css

我将文本放在 <textarea> 中,如下所示:

第一天1-一个苹果.2-一橙.3-两杯牛奶.

但它显示在 <label> 中,如下所示:

第一天 1- 一个苹果.2-一橙.3- 两杯牛奶.

如何使它看起来与 <textarea> 中的一样?

解决方案

给标签 white-space: pre-wrap 它将像文本区域一样换行

textarea {高度:70px;}标签 {空白:预包装;}

<textarea>第一天1-一个苹果.2-一橙.3-两杯牛奶.</textarea><br><br><标签>第一天1-一个苹果.2-一橙.3-两杯牛奶.</label>

<小时>

除了 white-space 属性结合换行符(例如 )之外,HTML 换行的方法是使用
;
,在这里添加一个小示例,它们是如何工作和不同的.

注意,即使是空格也可以使用 e.g.white-space: pre,如内联"代码示例中所示

var sample_script = document.querySelector('.sample.script');var name = "一二三";var name1 = name.replace(//g, '
');var name2 = name.replace(//g, '<br>');sample_script.innerHTML += name1;sample_script.innerHTML += "<br><br>";sample_script.innerHTML += name2;

div.pre {空白:pre;}/* 这个演示的样式 */身体{显示:弯曲;}.sample {flex: 1;边距:0 20px;}

<div class="sample inline">排队<小时>

一二三</div><div class="pre">一二三</div></div><div class="示例脚本">脚本<小时></div>

I put text in a <textarea> like this:

First day
1-one apple.
2-one orange.
3-two cups of milk.

But it shows in a <label> like this:

First day 1- one apple. 2-one orange. 3- two cups of milks.

How do I make it look the same as in a <textarea>?

解决方案

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. ), 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, '
');
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>

相关文章