CSS表格着色问题:剩余空白表格无法设置为黄色
解决表格空白单元格无法设置黄色背景的问题
问题根源
你当前使用td:nth-child(3)来设置黄色背景,但表格中存在rowspan和colspan属性,导致不同<tr>下的<td>数量不一致,这个选择器只能选中每行的第3个<td>,无法覆盖所有需要黄色的空白单元格。
解决方案一:添加类标记(推荐)
给所有需要黄色背景的空白单元格统一添加yellow-bg类,然后在CSS中定义该类的样式,逻辑清晰且易于维护。
修改后的HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="Poop.css"> <title>DEE IS A SEXY BASTERD!!! </title> </head> <body> <h1>table arcoiris:</h1> <div> <table> <tr> <!-- Background red--> <th></th><th></th><th></th><th></th> </tr> <tr> <!-- Background orange add rowspan 2 to make 2 rows--> <td id="orange" rowspan="2"></td> <td class="yellow-bg"></td> <td class="yellow-bg"></td> <td class="yellow-bg"></td> </tr> <!-- Background LIGHT GREEN ADD A COLSPAN 2 FOR THE OTHER 2 COLUMNS--> <tr id="seguanda_f"> <td colspan="2"></td> <td class="yellow-bg"></td> </tr> <tr id="tercera_f"> <td class="yellow-bg"></td> <td class="yellow-bg"></td> <td id="mag" rowspan="2" colspan="2"></td> </tr> <tr> <td class="blueviolet"></td> <td class="blueviolet"></td> </tr> </table> <table><tr><td>Segunda tavla usada para esta anotacion</td></tr></table> </div> </body> </html>
修改后的CSS代码
div{ width: 80%; height: 30%; margin-right: 10%; margin-left: 10%; text-align: center; } table, tr{ width: 100%; margin: 10px; } th,td { height: 20px; } th { background-color: red;} #orange{ background-color: orange; } .yellow-bg { background-color: yellow; } #seguanda_f{ background-color: lightgreen; } #tercera_f { background-color: blue; } .blueviolet{ background-color: blueviolet;} #mag{ background-color: magenta;}
解决方案二:使用精准CSS选择器(无需修改HTML)
通过排除已有样式的单元格,直接给剩余空白单元格设置黄色背景:
div{ width: 80%; height: 30%; margin-right: 10%; margin-left: 10%; text-align: center; } table, tr{ width: 100%; margin: 10px; } th,td { height: 20px; } th { background-color: red;} #orange{ background-color: orange; } /* 排除已有样式的单元格,设置黄色 */ table tr td:not(#orange):not(.blueviolet):not(#mag):not(#seguanda_f td) { background-color: yellow; } #seguanda_f{ background-color: lightgreen; } #tercera_f { background-color: blue; } .blueviolet{ background-color: blueviolet;} #mag{ background-color: magenta;}
内容的提问来源于stack exchange,提问作者Mihye
相关产品推荐
相关产品推荐

