如何使用CSS类在第一,第二或第三个html元素中选择子元素?

时间:2014-04-04 10:10:28

标签: html css

我想在CSS中选择锚标签。出于以下html文档的目的,我做了同样的事情。

我的html文档在这里:

<div class="first">
   <center><a href="http://www.google.com">The first link </a></center>
</div>

<div class="second">
   <center><a href="http://www.fb.com">The second link</a></center>
</div>

<div class="third">
   <center><a href="http://www.stackoverflow.com">The third link</a></center>
</div>

现在我要选择所有标签。我试着用这种方式:

body a:first-child:hover//The first child
{
    font-size:30px;
    color:yellow;
}
body a+a:hover  //the second child
{
    font-size:40px;
    color:red;
}
body a+a+a:hover  //the third child
{
    font-size:50px;
    color:#fff;
}

但我得错了结果该怎么办?

7 个答案:

答案 0 :(得分:4)

您的<a>元素不是兄弟姐妹(或兄弟姐妹),因此相邻的兄弟选择器(+)不适用于它们。

div元素是兄弟姐妹。

body div:first-child a:hover//The first child
{
    font-size:30px;
    color:yellow;
}
body  div+div a:hover  //the second child
{
    font-size:40px;
    color:red;
}
body div+div+div a:hover  //the third child
{
    font-size:50px;
    color:#fff;
}

您没有使用,也不需要使用类。

答案 1 :(得分:4)

您可以轻松选择如下:

.first a:first-child:hover//The first child
{
    font-size:30px;
    color:yellow;
}
.second a:nth-child(2):hover  //the second child
{
    font-size:40px;
    color:red;
}
.third a:nth-child(3):hover  //the third child
{
    font-size:50px;
    color:#fff;
}

对于现代浏览器,第二个使用a:nth-child(2),第三个使用a:nth-child(3)

希望这会有所帮助。

答案 2 :(得分:3)

.first{
font-size:30px;
color:yellow;
}
.first a:hover{
    font-size:40px;
    color:red;
}
 .second a:hover{
font-size:40px;
color:red;
}
.third a:hover{
    font-size:50px;
    color:#fff;
}

答案 3 :(得分:1)

你真的不需要任何课程,你可以使用:nth-child(n) - 选择器(参见this获取参考资料。)

此外,不需要使用body选择器(声明body是a的父元素)。正文是页面中每个可见元素的父元素,因此将其添加到选择器层次结构中并没有多大意义。

但是,如果您想使用已有的课程,可以执行以下操作:

.first a:hover
{
    font-size:30px;
    color:yellow;
}    
.second a:hover
{
    font-size:40px;
    color:red;
}
.third a:hover
{
    font-size:50px;
    color:#fff;
}

答案 4 :(得分:0)

body a {
//your rules here
}

这将选择您网站中的所有锚标记。

答案 5 :(得分:0)

直接定位锚点:

a {
    color: pink;
}

设置悬停和访问的样式:

a:focus,
a:hover {
    color: green;
}

a:visited {
    color: blue;
}

除此之外:您似乎需要学习基本的CSS。我建议&#34; CSS Diner&#34;在http://flukeout.github.io/可能是一个很好的练习。

答案 6 :(得分:0)

使用与div class元素的关联

.first a:hover//The first child
{
    font-size:30px;
    color:yellow;
}
.second a:hover  //the second child
{
    font-size:40px;
    color:red;
}
.third a:hover  //the third child
{
    font-size:50px;
    color:#fff;
}
相关问题