html - 为什么第 nth-child 应用于所有按钮?

标签 html css css-selectors

这是一个 example of my HTML and CSS .在我的一生中,我无法弄清楚为什么第二条规则适用于所有按钮,而不仅仅是前三个。

HTML

<div id="test">
<ul>
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
<li><button>4</button></li>
<li><button>5</button></li>
<li><button>6</button></li>
    </ul>
</div>

CSS

#test button
{
    background-color: blue;
}

#test button:nth-child(-n + 3) 
{
    background-color: red;
}

#test button:hover {
    background-color: green;
}

最佳答案

您将 nth-child 应用于错误的元素:每个 button 只有 1 个子元素。你的意思是定位 li 元素:

#test ul li:nth-child(-n + 3) button
{
    background-color: red;
}

http://jsfiddle.net/fCFEn/3/

关于html - 为什么第 nth-child 应用于所有按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12252916/

相关文章:

html - 为什么我的第一个子选择器不能处理具有指定类的选择中的第一个元素?

python - 使用 ID 的 css 选择器在 scrapy 中不起作用

jquery - 在 CSS 中选择具有特定类的序列的第一个和最后一个元素

css - django-plotly-dash div 大小太小,不会改变

javascript - 删除子元素jquery

javascript - 使用 DataTable 插件获取具有特定类的表的所有 td 值

php - 基于PHP/MySQL生成x个html元素

css - 有没有办法让第二行文本垂直填充?

html - 斜体选项

javascript - 元素移动时悬停不正确