如何高亮段落的第一行

在本指南中,你将了解如何高亮段落中的第一行文本,即使你不知道该行有多长。

¥In this guide you will find out how to highlight the first line of text in a paragraph, even if you don't know how long that line will be.

设置第一行文本的样式

¥Styling the first line of text

你希望将段落的第一行放大并加粗。在第一行周围包裹 <span> 意味着你可以对其进行样式设置,但是,如果第一行由于视口尺寸较小而变短,则样式化的文本将包裹到下一行。

¥You would like to make the first line of a paragraph larger and bold. Wrapping a <span> around the first line means that you can style it however, if the first line becomes shorter due to a smaller viewport size, the styled text will wrap onto the next line.

使用伪元素

¥Using a pseudo-element

pseudo-element 可以代替 <span>;然而,它更灵活 - 一旦浏览器渲染了内容,就会计算伪元素选择的确切内容,因此即使视口大小发生变化它也能工作。

¥A pseudo-element can take the place of the <span>; however, it is more flexible — the exact content selected by a pseudo-element is calculated once the browser has rendered the content, so it will work even if the viewport size changes.

在这种情况下,我们需要使用 ::first-line 伪元素。它选择每个段落的第一个格式化行,这意味着你可以根据需要设置其样式。

¥In this case we need to use the ::first-line pseudo-element. It selects the first formatted line of each paragraph, meaning that you can style it as you require.

注意:所有伪元素都以这种方式起作用。它们的行为就像你已将元素插入到文档中一样,但它们会根据运行时显示的内容动态地执行此操作。

¥Note: All pseudo-elements act in this way. They behave as if you had inserted an element into the document, but they do so dynamically based on the content as it displays at runtime.

将伪元素与其他选择器组合

¥Combining pseudo-elements with other selectors

在上面的示例中,伪元素选择每个段落的第一行。要仅选择第一段的第一行,你可以将其与另一个选择器结合使用。在本例中,我们使用 :first-child pseudo-class。如果 .wrapper 的第一个子项是一个段落,这允许我们选择该第一个子项的第一行。

¥In the example above, the pseudo-element selects the first line of every paragraph. To select only the first line of the first paragraph, you can combine it with another selector. In this case, we use the :first-child pseudo-class. This allows us to select the first line of the first child of .wrapper if that first child is a paragraph.

注意:将伪元素与 complexcompound 选择器中的其他选择器组合时,伪元素必须出现在它们出现的选择器中的所有其他组件之后。

¥Note: When combining pseudo-elements with other selectors in a complex or compound selector, the pseudo-elements must appear after all the other components in the selector in which they appear.

也可以看看