使用nth-child()选择器设置按钮样式时为何全部按钮变红?
Ah, I see the issue here! Let's break down why your current CSS isn't working as expected, then fix it step by step.
The Problem with :nth-child()
The :nth-child() selector counts all child elements of the parent element, not just elements of the same type. In your HTML, every <button> is wrapped inside a <p> tag, and each <p> is the first (and only) child of its own parent container. That means every button is the 1st child of its immediate <p> parent—so .k-klas button:nth-child(1) matches every single button, which is why all of them show up red.
Let's clarify your HTML hierarchy first to make this clearer:
<div class="k-klas"> <!-- First button's container --> <div> <p> <button>Inschrijven</button> </p> </div> <!-- Container for the second and third buttons --> <div> <div> <p> <button>Inschrijven</button> </p> <!-- Second button --> </div> <div> <p> <button>Inschrijven</button> </p> <!-- Third button --> </div> </div>
The Fix
To target each button individually, you need to first target their ancestor containers using :nth-child(), then select the button inside those containers. Here's the corrected CSS:
/* Target the first button (inside .k-klas's first direct child div) */ .k-klas > div:nth-child(1) button { background: #f00; } /* Target the second button (inside the first child div of .k-klas's second direct child) */ .k-klas > div:nth-child(2) > div:nth-child(1) button { background: #0f0; } /* Optional: Target the third button if needed */ .k-klas > div:nth-child(2) > div:nth-child(2) button { background: #00f; }
Simplification Tip (For Future Refactors)
If you ever restructure your HTML to have all button containers at the same level (e.g., adding a shared class like btn-wrapper to each container), you can simplify the code even more:
<div class="k-klas"> <div class="btn-wrapper"><p><button>Inschrijven</button></p></div> <div class="btn-wrapper"><p><button>Inschrijven</button></p></div> <div class="btn-wrapper"><p><button>Inschrijven</button></p></div> </div>
.k-klas .btn-wrapper:nth-child(1) button { background: #f00; } .k-klas .btn-wrapper:nth-child(2) button { background: #0f0; } .k-klas .btn-wrapper:nth-child(3) button { background: #00f; }
内容的提问来源于stack exchange,提问作者TonHaarmans

