为什么第 n 个孩子选择器不起作用?

新手上路,请多包涵

我正在使用 nth-child 选择器为不同的社交图标添加背景图像。但是,所有图标都显示相同。我究竟做错了什么?

 .social-logo {
    display: inline-block;
    width: 24px;
    height: 24px;
    transition: background-image .2s;
}

#social-links div:nth-child(1) {
    background-image: url('https://mysql-raigovind93.c9users.io/Cally%20Dai//img/footer/logo-linkedin.svg');
}

#social-links div:nth-child(1):hover {
    background-image: url('https://mysql-raigovind93.c9users.io/Cally%20Dai//img/footer/logo-linkedin-copy.svg');
}

#social-links div:nth-child(2) {
    background-image: url('https://mysql-raigovind93.c9users.io/Cally%20Dai//img/footer/logo-dribbble.svg');
}

#social-links div:nth-child(2):hover {
    background-image: url('https://mysql-raigovind93.c9users.io/Cally%20Dai//img/footer/logo-dribbble-copy.svg');
}

#social-links div:nth-child(3) {
    background-image: url('https://mysql-raigovind93.c9users.io/Cally%20Dai//img/footer/logo-email.svg');
}

#social-links div:nth-child(3):hover {
    background-image: url('https://mysql-raigovind93.c9users.io/Cally%20Dai//img/footer/logo-email-copy.svg');
}

#social-links div:nth-child(4) {
    background-image: url('https://mysql-raigovind93.c9users.io/Cally%20Dai//img/footer/logo-insta.svg');
}

#social-links div:nth-child(4):hover {
    background-image: url('https://mysql-raigovind93.c9users.io/Cally%20Dai//img/footer/logo-insta-copy.svg');
}
 <div id="social-links">
  <a href=""><div class="social-logo"></div></a>
  <a href=""><div class="social-logo"></div></a>
  <a href=""><div class="social-logo"></div></a>
  <a href=""><div class="social-logo"></div></a>
</div>

原文由 Govind Rai 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 365
2 个回答

nth-child 选择器计算兄弟姐妹(即具有相同父元素的元素)。

在您的 HTML 结构中, div.social-logo 始终是 --- a --- 的第一个、最后一个和唯一的孩子。所以 nth-child 只有一个元素要计算。

但是,有多个锚元素,它们都是兄弟元素( #social-links 的子元素),因此 nth-child 可以定位每个元素。

 #social-links a:nth-child(1) div
#social-links a:nth-child(2) div
#social-links a:nth-child(3) div
              .
              .
              .

原文由 Michael Benjamin 发布,翻译遵循 CC BY-SA 3.0 许可协议

在“:”之前添加空格示例:-

 tr :nth-child(2)
{
    text-align: right;
}

原文由 Naresh Bisht 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题