首页 > 解决方案 > 如何仅使用 CSS 将 content:"NEW" 添加到第 2 和第 3 段?

问题描述

  1. 帮助我将 content="NEW" 与 css 一起使用,但仅限于第 2 和第 3 段。
  2. 我不能更改 html 代码。
  3. 如果可能,请使用伪类。
<div id="first-div">
  <h2>Subheading</h2>
  <p>Paragraph 2</p> <!-- i need to add content here-->
  <p>Paragraph 3</p> <!--and here -->
  <div id="second-div">
     <h3>Sub subheading</h3>
     <p>Paragraph 4</p>
     <p>Paragraph 5</p>
     <p>Paragraph 6</p>
     <p>Paragraph 7</p>
     <p>Paragraph 8</p>
  </div>
</div>
<p>Paragraph 9</p>
<p>Paragraph 10</p>

标签: csscss-selectors

解决方案


您要做的是首先#first-div使用直接后代运算符 ( ) 查看并深入了解其子项>

如果您需要 2 个特定元素,则可以将直接子运算符与nth-child函数一起使用。

#first-div > p:nth-child(2):after,
#first-div > p:nth-child(3):after {
  color: red;
  content: "NEW";
}

如果您需要p下的所有标签#first-div,只需选择所有标签

#first-div > p:after {
  color: red;
  content: "NEW";
}

推荐阅读