如何在HTML中仅修改单个DataFrame生成的表格样式?
解决方法
要给两个DataFrame生成的表格设置不同样式,核心是利用pandas.DataFrame.to_html()的classes参数给每个表格绑定独立的CSS类,再针对类编写不同样式即可,具体操作如下:
1. 给表格指定自定义类
修改to_html()的调用逻辑,通过classes参数为两个表格分别设置不同的类名,比如table-style-1和table-style-2:
html = f''' <!DOCTYPE html> <html lang ="pl"> <head> <title>some title</title> </head> <style> /* 第一个表格的专属样式 */ .table-style-1 {{ width: 30%; text-align: center; border-collapse: collapse; margin-left: 30px; }} .table-style-1 td, .table-style-1 th {{ border: 1px solid #EEEEEE; padding: 5px 15px; }} .table-style-1 tbody td {{ font-size: 13px; }} .table-style-1 thead th {{ font-size: 15px; font-weight: bold; text-align: left; }} .table-style-1 tfoot td {{ font-size: 14px; }} /* 第二个表格的独立样式(可完全自定义) */ .table-style-2 {{ width: 60%; text-align: right; border-collapse: separate; margin: 20px auto; border: 2px solid #333; }} .table-style-2 td, .table-style-2 th {{ border: 1px solid #999; padding: 8px 20px; }} .table-style-2 tbody td {{ font-size: 14px; color: #555; }} .table-style-2 thead th {{ font-size: 16px; font-weight: normal; background-color: #f0f0f0; text-align: center; }} </style> <body> some text....... {DF.to_html(classes="table-style-1")} some text....... {DF2.to_html(classes="table-style-2")} </body> </html> '''
2. 关键说明
to_html(classes="类名")会给生成的<table>标签自动添加class="类名"属性,让CSS可以精准定位单个表格,不会影响其他表格样式。- 你原代码里的
tablek tbody td是笔误,已修正为正确的table tbody td格式。 - 第二个表格的样式可根据需求自由调整,比如宽度、对齐方式、边框颜色、背景色等,完全和第一个表格区分开。
内容的提问来源于stack exchange,提问作者mlodycezar
相关产品推荐
相关产品推荐

