首页 > 解决方案 > 使用 CSS 插入可选的自动换行点

问题描述

我正在尝试格式化最后有参考的报价。我的标记如下所示:

<p class=quotation>
    "Your time is limited, so don't waste it living someone else's life.
    Don't be trapped by dogma – which is living with the results of 
    other people's thinking."<span class=reference>Steve Jobs</span>
</p>

span我在使用 CSS::before伪元素之前插入了一个破折号。但是,换行符有点难看。我希望引号本身没有换行符,所以我的 CSS 目前看起来像这样:

.quotation .reference::before {
    content: '—';
}
.quotation .reference {
    white-space: nowrap;
}

不幸的是,这意味着最后一个词(在本例中为“thinking.”)会附加到破折号并换行。

我希望发生两件事:

我试过用 插入一个零宽度的空格content: '\200B—';,但这似乎根本没有效果。

有没有办法在纯 CSS 中实现这一点?

在此代码段中,div可调整大小,因此您可以查看未插入换行符的方式。

.quotation .reference::before {
  content: '—';
}
.quotation .reference {
  white-space: nowrap;
}


/* make div resizable to see the effect */

div {
  resize: both;
  overflow: scroll;
  border: 1px solid black;
  padding: 1em;
}
<div>
  <p class=quotation>
    "Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma – which is living with the results of other people's thinking."<span class=reference>Steve Jobs</span>
  </p>
</div>

标签: css

解决方案


只需使其inline-block避免附加效果:

.quotation .reference::before {
  content: '—';
}
.quotation .reference {
  white-space: nowrap;
  display:inline-block;
}


/* make div resizable to see the effect */

div {
  resize: both;
  overflow: scroll;
  border: 1px solid black;
  padding: 1em;
}
<div>
  <p class=quotation>
    "Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma – which is living with the results of other people's thinking."<span class=reference>Steve Jobs</span>
  </p>
</div>


推荐阅读