2012-06-23 37 views
0

我嘗試創建與第一個孩子和最後一個子項目的樣式,但我遇到了一個問題。第一個孩子和最後一個孩子與CSS3僞財產

在使用第一個孩子的時候,因爲之前有強的項目所以不適用風格。但我的最後一個孩子工作正常。

HTML:

<br /> 
<h2 class="title_block">Info <strong>1</strong> 
    <span class="title_block_info">+2</span> 
    <span class="title_block_info">+1</span> 
</h2>​ 

CSS:

h2 .title_block_info, 
h2 strong { 
    border: 1px solid #000; 
} 
h2 .title_block_info:first-child { 
    border-radius: 10px 0 0 10px; 
} 
h2 .title_block_info:last-child { 
    border-radius: 0 10px 10px 0; 
}​ 

這裏舉例:http://jsfiddle.net/mYKRW/

人知道爲什麼發生的嗎?

感謝,

回答

3

這是因爲你有一個「強有力的」標籤的第一個孩子,而不是title_block_info類,你所追求的。 first-child只有在它實際上是元素的第一個子元素時纔有效。

這工作

<h2 class="title_block"> 
    <span class="title_block_info">+2</span> 
    <span class="title_block_info">+1</span> 
</h2>​ 

http://jsfiddle.net/mYKRW/1/


如果你需要一個強大的文本在那裏,你可以試試這個,注意我是如何包裝你的兩個跨度每日新聞在另一個span標籤。這將允許您使用的第一孩子,最後孩子

h2 .title_block_info, 
h2 strong { 
    border: 1px solid #000; 
} 
h2 span .title_block_info:first-child { 
    border-radius: 10px 0 0 10px; 
} 
h2 span .title_block_info:last-child { 
    border-radius: 0 10px 10px 0; 
}​ 
<h2 class="title_block"> 
    Info <strong>1</strong> 
    <span> 
     <span class="title_block_info">+2</span> 
     <span class="title_block_info">+1</span> 
    </span> 
</h2>​ 

http://jsfiddle.net/mYKRW/6/


最後,如果你想保持你的HTML完全一樣,你可以使用first-of-type僞類你想要的,只是改變你的CSS。

h2 .title_block_info, 
h2 strong { 
    border: 1px solid #000; 
} 
h2 .title_block_info:first-of-type { 
    border-radius: 10px 0 0 10px; 
} 
h2 .title_block_info:last-of-type { 
    border-radius: 0 10px 10px 0; 
}​ 

http://jsfiddle.net/mYKRW/9/

+1

這是一個僞類。 – BoltClock

+2

你是對的,我很匆忙。妻子踢我離開電腦去踢足球......感謝你的支持。 –

2

:first-child僞類選擇來自選擇器.title_block_info所述第一匹配部件如果父元素的:first-child;正如你注意到的,這是行不通的,因爲還有另一個元素是父元素的第一個子元素。

在你的情況,你可以任意刪除strong元素正在上DOM中:first-child位置,或者你可以使用,取而代之的是,:first-of-type僞類:

h2 .title_block_info:first-of-type { 
    border-radius: 10px 0 0 10px; 
} 

JS Fiddle demo

如果你的HTML是要保持同樣可預測(在.title_block_info元素將始終遵循:first-child元素)你可以,而不是:

h2 :first-child + .title_block_info { 
    border-radius: 10px 0 0 10px; 
} 

JS Fiddle demo

參考文獻:

+0

只是爲了保持一致性,將它與':last-of-type'匹配。兼容性與':last-child'完全相同。 – BoltClock