2

我有一个带有两个 a 标签的 div 我想为第一个标签写 css。

这是HTML:。

<div id="Text">
    <br />                
    <a href="http://farsnews.com/newstext.php?nn=13920430001427#sthash.BOTOvYwM.dpuf">فارس نیوز</a>
    <a href="http://farsnews.com/newstext.php?nn=13920430001427#sthash.BOTOvYwM.dpuf">فارس نیوز</a>
</div>

这是我的CSS代码:

#Text a:last-child{
    text-decoration: none;
    color: red; /*rgb(18, 139, 235)*/
}
4

5 回答 5

5

试试这个

#Text a:first-of-type{
    /* css */
}

这将选择<a>#Text 中的第一个标签

于 2013-07-24T09:37:55.233 回答
4

问题是a不是其父级中的第一个孩子DIV#text 。CSS first-child 伪类的操作如下:

The :first-child CSS pseudo-class represents any element that is the first child element of its parent.

当从字面上准备好时,它只会应用于作为其父元素中的第一个子元素的元素。当您向其中添加其他类选择器时,它不会考虑您(心理上)创建的上下文。

应用伪类时,浏览器不理解选择器创建的上下文。基本上,它检查元素是否与选择器匹配#text a,然后提出问题,“这是父项中的第一个子项吗?”。它在没有考虑上述选择器的情况下提出这个问题。在您的情况下,答案是否定的,因为在 first 之前还有另一个元素a。那是<br/>(同样的事情last-child也适用)

在您的示例中,该元素<br/>实际上是第一个孩子。

所以结论是——

如果您想为其赋予样式,a:first-child则它必须是其父级的第一个子级,即DIV#text

现在你的第一个孩子是BR,所以请删除它,

否则分配

#Text a.q {
  ...
}

要不然

#Text a:first-of-type {...}

The :first-of-type selector is supported in all major browsers, except IE8 and earlier.
于 2013-07-24T09:34:16.660 回答
3
#Text a.q {
  //css
}

你可以这样做

于 2013-07-24T09:32:04.597 回答
1

你可以写如下:

div a.q {
  text-decoration: none;
   color: red; /*rgb(18, 139, 235)*/
}

或者

  #Text a.q {
      text-decoration: none;
       color: red; /*rgb(18, 139, 235)*/
    }
于 2013-07-24T09:36:35.143 回答
0

试试这个

#Text a:first-child{
    /*your css */
}
于 2013-07-24T09:33:20.423 回答