如何在我的代码中使用第一个孩子?

时间:2014-03-05 14:26:17

标签: html css pseudo-class css-selectors

在这个示例http://jsfiddle.net/eFhRE/1/中,我不想在第一个孩子的帮助下使用id shoshone red制作一个标签。必须只是带有id shoshone的标签,并且只能使用:first-child。其余的标签必须保持蓝色。

这是html代码:

<ul>
  <li class="mosonkhani">
    <a id="shoshone" href="#">Potsmare</a>
    <ul>
      <li><a href="#">Lorem</a></li>
      <li><a href="#">Ipsum</a></li>
      <li><a href="#">Dolores</a></li>
      <li><a href="#">Quiddam</a></li>
    </ul>
  </li>
</ul>

这是我尝试过的css代码:

a { color:#00f; }
.mosonkhani:first-child {
  color:#f00;
}

怎么做?

7 个答案:

答案 0 :(得分:3)

.mosonkhani > :first-child {
  color:#f00;
}

您希望第一个孩子 .mosonkhani。你所拥有的是一个带有类的元素 mosonkhani这也是第一个孩子。

http://jsfiddle.net/eFhRE/3/

答案 1 :(得分:0)

.mosonkhani > a:first-child {...}

.mosnokhani:first-child会给每个元素(使用class =&#34; mosonkhani&#34;),这是元素中第一个孩子的红色属性。

嗯.mosonkhani&gt;一个{...}也适用于这种情况。

答案 2 :(得分:0)

你不需要第一个孩子。

a { color:#00f; }

.mosonkhani > a {
  color:#f00;
}

http://jsfiddle.net/eFhRE/6/

答案 3 :(得分:0)

Pseudo class :first-child 匹配其前缀中的第一个元素。

您的代码将匹配文档中的第一个“.mosonkhani”元素。

如果您必须在任何.mosokhani中选择第一个' a '(链接)元素,请使用:

.mosonkhani a:first-child
{
    color: #f00;
}

答案 4 :(得分:0)

没有理由使此宽度first-childnth-child

复杂化

你的锚标签有一个ID ......用它

<强> CSS

#shoshone {
    color:red;
}

JSFiddle

答案 5 :(得分:-1)

您使用:first-child错误。

.mosonkhani > a:first-child {
  color:#f00;
}

那应该做你想要的。

你的小提琴,更新:http://jsfiddle.net/jeffijoe/eFhRE/2/

first-child将为您提供所有选择器目标的第一个实例。我个人认为first-child是一个误导的名字。

答案 6 :(得分:-1)

.mosonkhani>a {
    color:#f00;
}

是。我知道我没有使用第一个孩子。