第一个孩子和最后一个孩子与CSS3伪财产

问题描述:

我尝试创建与第一个孩子和最后一个子项目的样式,但我遇到了一个问题。第一个孩子和最后一个孩子与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/

人知道为什么发生的吗?

感谢,

这是因为你有一个“强有力的”标签的第一个孩子,而不是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

你是对的,我很匆忙。妻子踢我离开电脑去踢足球......感谢你的支持。 –

: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