【问题标题】:Why doesn't this CSS :first-child selector work?为什么这个 CSS :first-child 选择器不起作用?
【发布时间】:2011-09-29 05:43:25
【问题描述】:

我正在从事一个 Asp.Net MVC 3 项目,但我遇到了难题,为什么这不能像我认为的那样工作。

我的标记是:

<fieldset>
    <input type="hidden" value="2">
    <div class="editor-label"> 
        <label for="Name"> Name</label>
    </div>
    ...
</fieldset>

我的 CSS 是:

.display-label, .editor-label
{
    margin: 0.8em 0 0 0;
    font-weight: bold;
    display: inline;
}

fieldset > div:first-child
{
    margin: 0;
}

我要做的就是让字段集中的第一个 div 的边距为 0。我认为选择器 fieldset &gt; div:first-child 会将样式应用于“字段集的第一个子项,其类型为 div”,但显然有些事情正在躲避我。

我已经在 IE9/FF/Chrome 中尝试过这个,所以它不是一个旧的浏览器会弄乱我的选择器。

谢谢。

【问题讨论】:

  • 尝试字段集 > div.editor-label:first-child{margin-top:0}
  • 似乎在这里工作 jsfiddle.net/VcRyL 检查你的 CSS 看看是否没有覆盖此规则的属性规则
  • @AndreDublin 不起作用:jsfiddle.net/5dAKL/1

标签: css css-selectors


【解决方案1】:

fieldset &gt; div:first-child 表示“选择fieldset 的第一个子元素如果它是div”。

并不表示“选择fieldset中的第一个div”。

本例中的第一个孩子是&lt;input type="hidden" value="2"&gt;

要在不更改 HTML 的情况下选择 div,您需要使用 fieldset &gt; div:first-of-type

不幸的是,虽然:first-child 得到广泛支持,但:first-of-type 仅适用于 IE9+ 和其他现代浏览器。

因此,在这种情况下,最好的解决方法是继续使用fieldset &gt; div:first-child,并简单地移动&lt;input type="hidden" value="2"&gt;,这样它就不是第一个孩子了。

【讨论】:

  • 啊,这更有意义。我不知道&gt; div:first-child 也意味着“IF it's a div”,我只是认为它总是选择第一个匹配的孩子。我将不得不重新排列标记,因为我的客户端现在卡在 IE8 上。谢谢!
猜你喜欢
  • 2012-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-11
  • 2013-01-23
  • 2011-06-30
  • 2017-07-05
  • 2012-05-26
相关资源
最近更新 更多