第一个直接子项的css选择器 [英] css selector for first direct child only

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

问题描述

我有以下html

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

和以下样式:

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

由于某些原因,我不明白这种风格被应用于sub content 1 < div& 以及header < div>

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>.

我认为样式上的选择器只适用于带有section类的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?

推荐答案

你发布的字面意思是找到任何内部的div并且是他们父母的第一个孩子。 sub包含一个与该描述匹配的标签。

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.

我不知道你是否想要主div的两个孩子。如果是这样,请使用:

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

使用>

请注意,所有主流浏览器都支持这种方法,除IE6外。如果IE6支持是任务关键的,你将不得不添加类到子div,并使用它,而不是。否则,不值得关心。

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天全站免登陆