是否只有第一个直接子级的 CSS 选择器? [英] Is there a CSS selector for the first direct child only?

查看:22
本文介绍了是否只有第一个直接子级的 CSS 选择器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下html

<div class="section"><div>标题</div>

内容<div>子内容1</div><div>子内容2</div></div></div>

还有如下风格:

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

由于某种原因,我不明白该样式正在应用于 "sub contents 1" <div> 以及 "标题" <div>.

我认为样式上的选择器仅适用于具有名为section"的类的 div 的第一个直接子级.如何更改选择器以获得我想要的?

解决方案

您发布的字面意思是查找位于部分 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.

这篇关于是否只有第一个直接子级的 CSS 选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆