为什么nth-child选择器不起作用?

Gov*_*Rai 11 html css css-selectors

我正在使用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');
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Mic*_*l_B 18

所述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 
              .
              .
              .
Run Code Online (Sandbox Code Playgroud)

  • 啊,我花了一些时间来消化它,但你是绝对正确的。在这种情况下,您是否会建议我为每个 div 添加一个类,因为此规则集(至少对我而言)不是那么易读。 (2认同)

Nar*_*sht 8

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

tr :nth-child(2)
{
    text-align: right;
}
Run Code Online (Sandbox Code Playgroud)