我正在将一些带有空行的文本(来自数据库)推入一个p元素:

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

.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....

它显示为:

enter image description here

我试着把P改成DIV,但同样的问题.关于如何用css显示输出P中数据的空行,有什么建议吗?

推荐答案

您可以使用white-space css属性并将其设置为pre个、pre-line个或pre-break等值,具体取决于您希望文本的行为方式,以保留空白.

以下是2023-08-11年的MDN docs on white-space个国家的节选.

white-space属性值可以指定为从下面的值列表中 Select 的单个关键字,也可以指定为表示white-space-collapsetext-wrap属性速记的两个值.

  • normal

    • :空白的序列被折叠.源中的换行符与其他空白字符的处理方式相同.根据需要断开线条以填充线条框.
  • nowrap

    • : Collapses white space as for normal个, but suppresses line breaks (text wrapping) within the source.
  • pre

    • :保留了空白序列.只在源代码中的换行符和<br/>个元素处换行.
  • pre-wrap

    • :保留了空白序列.换行符、<br/>和填充行框所需的行断开符.
  • pre-line

    • :空格的序列被折叠.换行符、<br/>和填充行框所需的行断开符.
  • break-spaces

    • : The behavior is identical to that of pre-wrap个, except that:

      • 任何保留的空白序列都会占用空间,包括行尾.
      • 在每个保留的空白字符之后都有换行的机会,包括在空白字符之间.
      • 这种保留的空间会占用空间,不会悬挂,因此会影响盒子的固有尺寸(min-content大小和max-content大小).
New lines Spaces and tabs Text wrapping End-of-line spaces End-of-line other space separators
normal Collapse Collapse Wrap Remove Hang
nowrap Collapse Collapse No wrap Remove Hang
pre Preserve Preserve No wrap Preserve No wrap
pre-wrap Preserve Preserve Wrap Hang Hang
pre-line Preserve Collapse Wrap Remove Hang
break-spaces Preserve Preserve Wrap Wrap Wrap

有关HTML和空格的更多详细信息,请参阅MDN - How whitespace is handled by HTML, CSS, and in the DOM.

// copied from the question
const textWithWhiteSpace = `to stay new and fresh even after over four decades in the business.

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

function App({ text }) {
  return <p className="biography">{text}</p>;
}

ReactDOM.render(<App text={textWithWhiteSpace} />, document.getElementById("root"));
.biography {
    font-size: 1.4rem;
    color: #333333;
    text-align: justify;
    /* preserve whitespace */
    white-space: pre;
}
<script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Css相关问答推荐

为什么图像加载请求没有显示在我的网络请求中?

当滚动到页脚时,是否可以隐藏固定元素?

如何使TWebPanel具有圆角?

根据现有值计算CSS变量的新值

Img 未拉伸以满足所需的纵横比

如何在 VS Code 中获得 JavaFX CSS 属性的自动完成功能?

before 元素的过渡效果

如何在变量中插入 SCSS 变量?

Material UI Modal 因背景而变暗

如何禁用 Angular Material Pagination 按钮的波纹效果?

在 WooCommerce 变体 Select 中转换属性文本以大写

使用 display:inline-block 渲染多行文本组件,行间有白色间隙

我怎样才能在某些区域制作一个单独的文本行,而在其他区域制作一个实心填充?

flex-start 和基线有什么区别?

Flexbox 列自底对齐

使用 CSS 强制侧边栏高度 100%(带有粘性底部图像)?

CSS3可以转换字体大小吗?

为什么 CSS 中的光标:指针效果不起作用

如何参加滚动事件?

脉动的心脏 CSS 动画