仅更新CSS

时间:2017-06-26 08:57:55

标签: html css

我想使用外部CSS更新/触摸HTML中第一次出现的元素。例如:



<section>
		<article>
		    <h2>20 CSS Best Practices</h2> 
			<p>
				<ul>
					<li>ABC</li>
					<li>XYZ</li>
				 </ul>
			 </p>
		</article>

		<article>
			<h2>CSS References</h2>
			<p>
				<ul>
					<li>ABC</li>
					<li>XYZ</li>	
				</ul>
			 </p>
		</article>
		
		<article>
			<h2>Additional References</h2>
			<p>
				<ul>
					<li>ABC</li>
					<li>XYZ</li>
				</ul>
			 </p>
		</article>
	</section>
&#13;
&#13;
&#13;

在上面的代码中,我只希望仅在第一个<h2>中触摸article的第一个匹配项,而不是在所有articles中。

但是使用first-of-type会更新所有<h2>。我知道有一种方法可以通过类或ID属性更新它,但我不想这样做。还有其他办法吗?

1 个答案:

答案 0 :(得分:2)

使用nth-of-type获取相同的

添加以下css部分

section article:nth-of-type(1) h2 {
  color: red;
}

&#13;
&#13;
section article:nth-of-type(1) h2 {
  color: red;
}
&#13;
<section>
  <article>
    <h2>20 CSS Best Practices</h2>
    <p>
      <ul>
        <li>ABC</li>
        <li>XYZ</li>
      </ul>
    </p>
  </article>

  <article>
    <h2>CSS References</h2>
    <p>
      <ul>
        <li>ABC</li>
        <li>XYZ</li>
      </ul>
    </p>
  </article>

  <article>
    <h2>Additional References</h2>
    <p>
      <ul>
        <li>ABC</li>
        <li>XYZ</li>
      </ul>
    </p>
  </article>
</section>
&#13;
&#13;
&#13;

您也可以使用first-of-type来获取

&#13;
&#13;
section article:first-of-type h2{
  color: red;
}
&#13;
<section>
  <article>
    <h2>20 CSS Best Practices</h2>
    <p>
      <ul>
        <li>ABC</li>
        <li>XYZ</li>
      </ul>
    </p>
  </article>

  <article>
    <h2>CSS References</h2>
    <p>
      <ul>
        <li>ABC</li>
        <li>XYZ</li>
      </ul>
    </p>
  </article>

  <article>
    <h2>Additional References</h2>
    <p>
      <ul>
        <li>ABC</li>
        <li>XYZ</li>
      </ul>
    </p>
  </article>
</section>
&#13;
&#13;
&#13;

first-child也可以使用

&#13;
&#13;
section article:first-child h2 {
  color: red;
}
&#13;
<section>
  <article>
    <h2>20 CSS Best Practices</h2>
    <p>
      <ul>
        <li>ABC</li>
        <li>XYZ</li>
      </ul>
    </p>
  </article>

  <article>
    <h2>CSS References</h2>
    <p>
      <ul>
        <li>ABC</li>
        <li>XYZ</li>
      </ul>
    </p>
  </article>

  <article>
    <h2>Additional References</h2>
    <p>
      <ul>
        <li>ABC</li>
        <li>XYZ</li>
      </ul>
    </p>
  </article>
</section>
&#13;
&#13;
&#13;