html - 为什么第 n 个 child 选择器不起作用?

标签 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');
}
<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>

最佳答案

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

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

但是,有多个 anchor 元素,它们都是兄弟元素(#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 
              .
              .
              .

关于html - 为什么第 n 个 child 选择器不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41867097/

相关文章:

html - 从中心开始后的伪元素 - CSS

javascript - 如何在不影响周围 div 的情况下放大父 div 并在悬停时显示隐藏的子 div

javascript - 单击 svg 元素时添加下拉菜单

php - 将视频添加为收藏夹的逻辑。

jquery - -moz-transition 在 chrome 中工作但在 firefox safari 中不工作,即请帮助我

javascript - 如何在浏览器缩放时动态定位和缩放 iframe

jquery - 智能手机和 table 的 CSS 外壳

Javascript - 让div随按钮滑动

css - 多个第 n 个子语句

python - 如何通过css选择器选择标签