如何在不重构HTML的情况下选中最后一个.title元素?
Great question! The problem with using :last-child here is that the last element inside .tabs is actually the .content div, not a .title—so that selector misses the mark. But don't worry, there's a reliable way to target the last .title element even when you add more later, no HTML restructuring required.
Best Solution: Use the :has() Pseudo-Class
Modern browsers support the :has() selector, which lets you target an element based on its sibling elements. For your case, we can select any .title that's immediately followed by something that isn't another .title—this will automatically be the last .title in your sequence before the .content (or any other non-.title element you add later).
Here's the CSS you need:
.tabs > .title:has(+ :not(.title)) { /* Add your styles here, e.g.: */ font-weight: bold; color: #2c3e50; }
This works seamlessly even if you add more .title elements like C, D, or E—it will always pick the last one before the non-title content.
Fallback for Older Browsers
If you need to support older browsers that don't have :has() (like Firefox versions before 121), you can use a structure-dependent trick. Assuming all .title elements come before the .content and there's only one .content in .tabs, you can use:
.tabs > .title:nth-last-child(2) { /* Your styles here */ }
Just keep in mind: this will break if you add any elements after .content, since it relies on the last .title being the second-to-last child of .tabs. The :has() method is definitely the more robust choice.
内容的提问来源于stack exchange,提问作者Sharon Chai

