我正在尝试根据它们在页面上的时间顺序外观来设置一组随机图像的样式,仅使用CSS,而没有任何html类(旧演示(。
由于该部分中的所有图像都是链接,因此我包装了<a>
...</a>
围绕img
标签,但现在 CSS 选择被破坏了!
我尝试了各种选择器,但都坏了(未选择,未应用正确的背景颜色(:
sponsor img:nth-child(1)
sponsor img:nth-of-type(1)
sponsor a img:nth-child(1)
a img:nth-child(1)
JSFIDDLE 损坏的时间顺序选择器的演示。我忽略了什么?谢谢!
通过将图像包装在<a>
中...</a>
标记,则img:nth-child(1)
无效。您应该改用a
标记上的:nth-child
属性:
sponsor a:nth-child(1) img{width:100%; background: Fuchsia}
sponsor a:nth-child(2) img{width: 49%; background: YellowGreen}
...
JsFiddle 演示
nth-child()
伪类以同一父类的所有子类为目标。
由于img
是sponsor
的子女,nth-child()
工作。
但是,当您将每个img
包装在锚元素中时,它们将成为a
的子项,而不再是sponsor
的子项。因此,nth-child()
失败了。
现在每个img
都是a
的第一个、最后一个和唯一的孩子,用nth-child()
来瞄准它们是没有意义的。
若要修复布局,nth-child()
需要定位sponsor
的新子项 - 定位点。
取而代之的是:
sponsor img:nth-child(2)
试试这个:
sponsor > a:nth-child(2) > img