如何修改CSS自定义Datatables表格头部的排序图标样式
Datatables自定义排序图标不生效修复方案
失效原因
你写的自定义样式没有生效,主要是两个原因:
- Datatables自带的默认样式优先级更高,直接覆盖了你写的低优先级CSS规则
- 表头单元格没有留出对应展示空间,导致图标和文字重叠,看起来没有渲染成功
修正后的代码
如果使用的是默认主题,用以下CSS即可:
/* 先清除默认图标,给左侧留出图标展示空间 */ table.dataTable thead th.sorting, table.dataTable thead th.sorting_asc, table.dataTable thead th.sorting_desc { background-image: none !important; padding-left: 22px !important; } /* 自定义升序图标 */ table.dataTable thead th.sorting_asc { background: url("替换为你的升序图标资源地址") no-repeat center left !important; } /* 自定义降序图标 */ table.dataTable thead th.sorting_desc { background: url("替换为你的降序图标资源地址") no-repeat center left !important; } /* 自定义未激活排序的双箭头图标 */ table.dataTable thead th.sorting { background: url("替换为你的未排序双箭头图标资源地址") no-repeat center left !important; }
如果你使用的是Bootstrap等第三方主题适配的Datatables版本,主题会用伪元素渲染排序图标,需要额外加规则隐藏伪元素:
table.dataTable thead th.sorting::before, table.dataTable thead th.sorting::after, table.dataTable thead th.sorting_asc::before, table.dataTable thead th.sorting_asc::after, table.dataTable thead th.sorting_desc::before, table.dataTable thead th.sorting_desc::after { display: none !important; }
注意事项
- 代码里的
!important是为了提升样式优先级,确保覆盖默认规则,不要省略 - 图标资源地址建议使用自己托管的资源,避免跨域、第三方资源失效问题
padding-left的数值可以根据你的图标大小调整,确保图标和文字不会重叠
内容的提问来源于stack exchange,提问作者Regual
相关产品推荐
相关产品推荐

