首页  >  文章  >  web前端  >  为什么我的第 n 个子选择器不能处理嵌套元素?

为什么我的第 n 个子选择器不能处理嵌套元素?

Linda Hamilton
Linda Hamilton原创
2024-10-28 11:04:02800浏览

 Why is my nth-child selector not working on nested elements?

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

您可能在使用第 n-child 选择器时遇到此问题造型目的。尽管使用此选择器将背景图像添加到不同的社交图标,但您会注意到所有图标都显示相同的外观。这表示您的代码中存在问题。

深入研究问题

第 n 个子选择器旨在根据特定元素在其中的位置来定位特定元素兄弟元素。但是,在您的代码中,选择器:

#social-links div:nth-child(1),
#social-links div:nth-child(2),
#social-links div:nth-child(3),
#social-links div:nth-child(4),

定位的是 #social-links 元素的子元素 div 元素。然而,这些 div 元素始终是其各自锚点 (a) 元素的唯一子元素。因此,第 n 个子选择器无法区分它们,因为它们都是其锚元素的第一个且唯一的子元素。

正确方法

纠正对于这个问题,您需要调整 nth-child 选择器以定位锚元素而不是 div 元素。通过这样做,您可以指定哪个锚元素应接收特定的背景图像:

#social-links a:nth-child(1) div { 
   background-image: url('path/to/image1.svg'); 
}
#social-links a:nth-child(2) div { 
   background-image: url('path/to/image2.svg'); 
}
#social-links a:nth-child(3) div { 
   background-image: url('path/to/image3.svg'); 
}
#social-links a:nth-child(4) div { 
   background-image: url('path/to/image4.svg'); 
}

此修改后的代码结构可确保每个锚元素根据其在同级锚元素中的位置接收预期的背景图像。

以上是为什么我的第 n 个子选择器不能处理嵌套元素?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn