繁体   English   中英

CSS子选择器不起作用

[英]Css child selector is not working

我正在研究子代选择器和子代选择器之间的区别。 根据我找到的文档以及这个问题, CSS Child和Descendant选择器我写了这个例子:

<div>
    <h2>h2 1</h2>
    <h2>h2 2</h2>
    <section>
    section
        <h1>h1 section's son
            <h2>h2 section's nephew</h2>
        </h1>
        <h2>h2 section's son</h2>
    </section>
    <h2>h2 3</h2>
    <h2>h2 4</h2>
</div>

CSS:

section > h2 {
    color:red;
}

(在这里拨弄: http : //jsfiddle.net/armdan/ksB6f/1/

我希望在此示例中不会选择“ h2节的侄子”,但它会被选中并变成红色。 我不明白我在想什么。

可能是因为h1包含h2是无效的。 如果将h1更改为可以包含h2的元素(例如div ,它将按您期望的那样工作:

<div>
    <h2>h2 1</h2>
    <h2>h2 2</h2>
    <section>
    section
        <div>h1 section's son
            <h2>h2 section's nephew</h2>
        </div>
        <h2>h2 section's son</h2>
    </section>
    <h2>h2 3</h2>
    <h2>h2 4</h2>
</div>

http://jsfiddle.net/Z5CeB/

背景: h1HTML5规范说,它只能包含文本和“短语元素” ,它们是:

  • 一种
  • EM
  • 强大
  • 标记
  • 简称
  • DFN
  • 一世
  • b
  • 小号
  • ü
  • VAR
  • SAMP
  • 大骨节病
  • SUP
  • q
  • 引用
  • 跨度
  • BDO
  • BDI
  • BR
  • WBR
  • 插件
  • 德尔
  • IMG
  • 宾语
  • IFRAME
  • 地图
  • 区域
  • 脚本
  • NOSCRIPT
  • 红宝石
  • 视频
  • 音频
  • 输入
  • textarea的
  • 选择
  • 按键
  • 标签
  • 产量
  • 数据列表
  • 凯基
  • 进展
  • 命令
  • 帆布
  • 时间
  • 仪表

有几件事...

  1. <h2>不能包含在<h1>
  2. section > h2选择<h2> ,该<h2>直接位于<section>而不是大子元素。 在后一种情况下,您需要使用section h2

解决方法将以这种方式更改您的代码以使其具有语义:

<div>
    <h2>h2 1</h2>
    <h2>h2 2</h2>
    <section>
    section
        <h1>h1 section's son</h1>
        <h2>h2 section's nephew</h2>
        <h2>h2 section's son</h2>
    </section>
    <h2>h2 3</h2>
    <h2>h2 4</h2>
</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM