2012-07-04 29 views
2
<!-- HTML --> 
<section class="row slide"> 
    <div class="span4"> 
     <h1> 
      <span>Some</span> 
      <br /> 
      <span>Title</span> 
     </h1> 
    </div> 
</section> 

<section class="row slide"> 
    <div class="span4"> 
     <h1> 
      <em>Some emphasis</em> 
      <br /> 
      <span>Some</span> 
      <br /> 
      <span>Title</span> 
     </h1> 
    </div> 
</section> 

<section class="row slide"> 
    <div class="span4"> 
     <h1> 
      <em>Some other emphasis</em> 
      <br /> 
      <span>Some</span> 
      <br /> 
      <span>Title</span> 
     </h1> 
    </div> 
</section> 


/* CSS */ 
section h1 span:first-child{ 
    color:#FF0033; 
    } 

我想針對第一<span><h1>標記,是在一個<section>容器,但只要<span>不是第一個子元素(如<em>),那麼它不會應用該規則。爲什麼我的:first-child css規則無法應用?

回答

9

:first-child選擇第一孩子。使用:first-of-type你的目的:

section h1 span:first-of-type { 
    color: #FF0033; 
} 
2

:first-child不引用元素是此類型的第一個孩子,但一般是其父的第一個孩子! Citing MDN on this

:first-child CSS僞類表示其父的第一個子元素的元素。

你需要的是:first-of-type選擇(MDN link)如下:

section h1 span:first-of-type{ 
    color:#FF0033; 
} 

Example fiddle