【问题标题】:Why is nth-child applying to all buttons?为什么 nth-child 应用于所有按钮?
【发布时间】:2023-03-13 12:11:01
【问题描述】:

这是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;
}

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-28
      • 2023-04-02
      • 2018-07-30
      • 2021-03-06
      • 2012-11-21
      • 2017-06-11
      相关资源
      最近更新 更多