如何为表格指定列设置背景色(不使用nth-child)
Absolutely doable—no need to doubt! Here are two straightforward CSS approaches that work seamlessly with strict DOCTYPE declarations:
Method 1: Use the :nth-child() Pseudo-Class (Cleanest, No HTML Changes)
Since Tuesday is your 3rd column (counting from 1), you can target all header and data cells in that column directly with CSS:
/* Target the Tuesday header cell */ table th:nth-child(3) { background-color: #e6f7ff; /* Swap this with your preferred color */ } /* Target all data cells in the Tuesday column */ table td:nth-child(3) { background-color: #e6f7ff; }
This works across all modern browsers and even older ones (like IE9+), so it’s totally safe with strict DOCTYPE. The :nth-child(3) selector picks every element that’s the 3rd child of its parent, which aligns perfectly with your fixed table structure.
Method 2: Add a Custom Class (More Explicit, Good for Dynamic Tables)
If you prefer clearer code or anticipate adjusting column order later, add a class to the Tuesday column’s cells in your HTML:
HTML Snippet:
<table> <thead> <tr> <th>LINKS</th> <th>Monday</th> <th class="tuesday-column">Tuesday</th> <th>Wednesday</th> <!-- ... remaining headers ... --> </tr> </thead> <tbody> <tr> <td><a href="#">Sample Link</a></td> <td>Day Data</td> <td class="tuesday-column">Day Data</td> <td>Day Data</td> <!-- ... remaining rows ... --> </tr> </tbody> </table>
CSS:
.tuesday-column { background-color: #e6f7ff; }
This method avoids relying on column positions, making it easier to maintain if your table structure ever changes.
Both approaches are fully compliant with strict DOCTYPE standards—no hacks or workarounds needed. Pick whichever fits your workflow best!
内容的提问来源于stack exchange,提问作者semicodin

