You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用CSS在P元素中显示数据库文本的空行?

如何在p元素中保留数据库文本的空行?

我将从数据库获取的带有空行的文本渲染到p元素中,代码如下:

<p className={styles.biography}>{loaderData.cast.biography} </p>

对应的CSS样式:

.biography {
    font-size: 1.4rem;
    color: #333333;
    text-align: justify;
}

但文本中的空行并未显示,例如数据库返回的文本开头为:

to stay new and fresh even after over four decades in the business.

Downey was born April 4, 1965 in Manhattan, New York....

实际渲染时空行消失,换成div元素问题依旧。如何通过CSS实现在p元素中显示数据里的空行?


解决方案

给.biography类添加white-space: pre-line;样式即可,修改后的CSS:

.biography {
    font-size: 1.4rem;
    color: #333333;
    text-align: justify;
    white-space: pre-line;
}

说明

  • pre-line会保留文本中的换行符(对应数据库里的空行),同时会合并连续空格,并自动换行以适应容器宽度,完全适配普通文本的排版需求。
  • 如果需要保留文本中的所有空格(比如缩进),可以改用white-space: pre-wrap;,但pre-line更适合大多数常规文本场景。

内容的提问来源于stack exchange,提问作者D. Rattansingh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 09:15:04