【问题标题】:CSS white-space: pre not working as expectedCSS 空白:pre 未按预期工作
【发布时间】:2017-04-26 04:04:06
【问题描述】:

我从服务器返回的文本包含回车(回车)。我问了一些人如何在多行中显示此文本,他们建议我使用white-space: pre

没有white-space: pre,还有其他方法可以多行显示文本吗?或者有什么方法可以让pre 表现得像一个段落,但有多行而没有额外的填充?

这是我所拥有的:

.gallery-Gcontainer {
  margin: 0 !important;
  padding: 0;
}
#genericpartTitle,
.content {
  padding-left: 20px;
}
.content .sidebar,
.content section {
  display: inline-block;
  width: 30%;
  border: none;
  vertical-align: top;
}
.content .sidebar img {
  width: 200px;
}
<div class="gallery-Gcontainer">
  <div class="header-area">
    <h3 id="genericpartTitle">my page</h3>
    <hr>
  </div>
  <div class="content">
    <div class="sidebar">
      <img class="img-sidebar" src="https://static.pexels.com/photos/30738/pexels-photo-30738.jpg" />
    </div>
    <section>
      <h5 class="item-title">Welcome to my first page</h5>
      <p style="white-space: pre" class="description">
        Hello, anything will go here, text will come from the server like this, and I need to display it on multiple lines.
      </p>
    </section>
  </div>
</div>

更新: Putting:white-space: pre-line 按照答案中的建议,解决了 padding left 问题,但 padding-top 仍然有很大的空间。

【问题讨论】:

    标签: html css


    【解决方案1】:

    white-space: pre-line代替white-space: pre

    来自 MDN:

    The white-space property

    white-space 属性用于描述内部的空白 元素被处理。

    正常 空白序列被折叠。源中的换行符作为其他空格处理。换行为 需要填充行框。

    nowrapnormal 一样折叠空格,但抑制文本中的换行符(文本换行)。

    pre 保留空白序列。仅在源中的换行符和&lt;br&gt; 元素处换行。

    pre-wrap 保留空白序列。在换行符处、&lt;br&gt; 处换行,并根据需要填充行框。

    pre-line 空格序列被折叠。在换行符处、&lt;br&gt; 处换行,并根据需要填充行框。

    另外,您提到的padding-top 问题并不是真正的填充。在查看您的代码时,似乎在行首至少有一个换行符。

    【讨论】:

    • 这行得通,那我为什么需要使用pre?如这个问题:stackoverflow.com/questions/41050367/…
    • 我为每个值添加了定义。
    • 是的,在你回答我之后,我从 MDN 读到过,但它没有提到任何关于填充的内容
    • @Michael_B,试试我的代码,去掉空格:pre,你会去掉填充
    • @Jacky,你提到的padding-top 问题并不是真正的填充。文本开头似乎至少有一个回车。
    【解决方案2】:

    如果可能的话,请使用下面的 CSS javascript 代码。

    var ss = " Hello`, anything will go here, text will come from the server like this, and I need to display it on multiple lines.";
    
    document.getElementById('test').innerHTML = ss.replace(/\n/g, '<br/>');  
    

    document.getElementById('test').innerHTML = ss.replace(/\n/g, '<br>\n');
    
    <p id="test"> </p>
    

    【讨论】:

    • 你能解释一下原因吗?
    • 因为当数据从 Internet Explorer 中的 textarea 附加到任何容器(如

      标签)时。当我们使用 lib html2pdf.bundle.js 将 HTML 转换为 PDF 时,空白 CSS 不适用于它,它也会产生问题。所以在这里你可以将新行替换为
      标签

    • 你的答案的解释属于 inside 你的答案,而不是在评论 under 你的答案。请编辑您的答案,然后删除您的评论。那么你的答案下就不需要任何cmet了。
    【解决方案3】:

    使用“display:block”作为您的 CSS 样式。这应该换行。

    <p style="display: block" class="description">
    

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签