且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否只有第一个直接子级的 CSS 选择器?

更新时间:2023-11-25 23:27:04

您发布的字面意思是查找位于部分 div 内并且是其父级的第一个子级的任何 div."sub 包含一个与该描述匹配的标签.

我不清楚你是否想要主 div 的两个孩子.如果是这样,请使用:

div.section >div

如果你只想要标题,使用这个:

div.section >div:第一个孩子

使用 > 将描述更改为:查找任何作为部分 div 的直接后代的 div",这就是您想要的.

请注意所有主流浏览器都支持此方法,IE6 除外.如果 IE6 支持是关键任务,则必须将类添加到子 div 并改为使用它.否则就不值得关心了.

I have the following html

<div class="section">
   <div>header</div>
   <div>
          contents
          <div>sub contents 1</div>              
          <div>sub contents 2</div>
   </div>
</div>

And the following style:

DIV.section DIV:first-child 
{
  ...
}

For some reason that I don't understand the style is getting applied to the "sub contents 1" <div> as well as the "header" <div>.

I thought that the selector on the style would only apply to the first direct child of a div with a class called "section". How can I change the selector to get what I want?

What you posted literally means "Find any divs that are inside of section divs and are the first child of their parent." The sub contains one tag that matches that description.

It is unclear to me whether you want both children of the main div or not. If so, use this:

div.section > div

If you only want the header, use this:

div.section > div:first-child

Using the > changes the description to: "Find any divs that are the direct descendents of section divs" which is what you want.

Please note that all major browsers support this method, except IE6. If IE6 support is mission-critical, you will have to add classes to the child divs and use that, instead. Otherwise, it's not worth caring about.

相关阅读

推荐文章