【问题标题】:Applying CSS classes to plugin-generated elements of the same tag?将 CSS 类应用于同一标签的插件生成元素?
【发布时间】:2018-05-01 12:43:20
【问题描述】:
基本上,我有一个插件可以生成一个由一个<ul> 标签和几个<li> 标签组成的HTML 菜单。我想为每个菜单项应用不同的背景颜色,但我无法将这些 CSS 类添加到每个列表项,因为它们是以编程方式生成的,因此无法直接访问。有没有办法将不同的类应用于同一标签的多个子元素?就我而言,无需访问插件文件。
【问题讨论】:
标签:
html
css
wordpress
plugins
【解决方案1】:
是的,有可能。
您可以使用nth-of-type(n) 选择器来定位不同的<li> 元素,而无需向生成的代码添加类。
body {font-size: 22px}
ul li:nth-of-type(1){background:red}
ul li:nth-of-type(2){background:blue}
ul li:nth-of-type(3){background:green}
ul li:nth-of-type(4){background:yellow}
ul li:nth-of-type(5){background:orange}
ul li:nth-of-type(6){background:purple}
ul li:nth-of-type(7){background:cyan}
ul li:nth-of-type(8){background:brown}
ul li:nth-of-type(9){background:pink}
<ul>
<li>Apple</li>
<li>Orange</li>
<li>Watermelon</li>
<li>Pear</li>
<li>Milk</li>
<li>Cheese</li>
<li>Bread</li>
<li>Jam</li>
<li>Sugar</li>
</ul>
您还可以使用页面上的其他元素来确保更改仅应用于您想要影响的元素。
示例:
body {
font-size: 22px
}
.foo ul li:nth-of-type(1) {
background: red
}
.foo ul li:nth-of-type(2) {
background: blue
}
.foo ul li:nth-of-type(3) {
background: green
}
.foo ul li:nth-of-type(4) {
background: yellow
}
<div class="bar">
<h1> First List (not modified)</h1>
<ul>
<li>Apple</li>
<li>Orange</li>
<li>Watermelon</li>
<li>Pear</li>
</ul>
</div>
<div class="foo">
<h1> Second List (modified)</h1>
<ul>
<li>Apple</li>
<li>Orange</li>
<li>Watermelon</li>
<li>Pear</li>
</ul>
</div>
<div class="bar">
<h1> Third List (not modified)</h1>
<ul>
<li>Apple</li>
<li>Orange</li>
<li>Watermelon</li>
<li>Pear</li>
</ul>
</div>