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

标签 html css label line-breaks

我将文本放在 <textarea> 中像这样:

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

但它显示在 <label> 中像这样:

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

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

最佳答案

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

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>


除了 white-space属性与换行符(例如 \n )相结合,HTML 换行方式是使用 <br> , 在此处添加一个小示例,了解它们的工作原理和不同之处。

请注意,即使是空格也可以使用例如white-space: pre ,如“内联”代码示例中所示

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>

关于html - 如何显示带有换行符的文本的标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36558282/

相关文章:

javascript - 如何将脚本的不同功能放在同一个html页面中?

css - 为什么我的自定义字体使用 font-face 渲染不同?

html - 响应式 - 图片上的文字

jquery - phonegap 和 jquery mobile 的 $.getScript 和 css 问题

html - 以类似的对齐方式设置表格中的文本

javascript - 在不同的文件上使用 JavaScript 变量

html - Bootstrap 模态形式太丑了

java - LWUIT 画家 : How to draw a line on top of a Image Label?

r - 自定义 ggplot2 Axis 和标签格式

jquery - 无法获得 <label> 元素的正确宽度或outerWidth