在Django中无法关联HTML星级评分与CSS文件的技术求助
解决Django中星级评分样式不生效的问题
问题核心原因
你的星级评分样式无法生效,主要源于三个关键问题:
- CSS使用了嵌套语法(类似Sass/LESS预处理器写法),但标准CSS不支持该结构,浏览器无法解析
- 父模板
base.html可能未正确引入main.css文件 - 未引入Font Awesome图标库,导致星级图标无法渲染,样式效果缺失
分步解决方案
1. 修复CSS嵌套语法
将main.css中#full-stars-example下的嵌套选择器展开为标准CSS写法,浏览器才能正确识别:
修改后的main.css相关代码:
#full-stars-example .rating-group { display: inline-flex; } #full-stars-example .rating__icon { pointer-events: none; } #full-stars-example .rating__input { position: absolute !important; left: -9999px !important; } #full-stars-example .rating__label { cursor: pointer; padding: 0 0.1em; font-size: 2rem; } #full-stars-example .rating__icon--star { color: orange; } #full-stars-example .rating__icon--none { color: #eee; } #full-stars-example .rating__input--none:checked + .rating__label .rating__icon--none { color: red; } #full-stars-example .rating__input:checked ~ .rating__label .rating__icon--star { color: #ddd; } #full-stars-example .rating-group:hover .rating__label .rating__icon--star { color: orange; } #full-stars-example .rating__input:hover ~ .rating__label .rating__icon--star { color: #ddd; } #full-stars-example .rating-group:hover .rating__input--none:not(:hover) + .rating__label .rating__icon--none { color: #eee; } #full-stars-example .rating__input--none:hover + .rating__label .rating__icon--none { color: red; }
2. 确认base.html正确引入CSS
在base.html的<head>标签内添加静态文件引入代码(路径需匹配你的实际静态文件目录):
{% load static %} <link rel="stylesheet" type="text/css" href="{% static 'main.css' %}">
若
main.css放在static/css/子目录下,路径改为{% static 'css/main.css' %}
3. 引入Font Awesome图标库
在base.html的<head>中添加图标库引入,因为星级评分依赖fa fa-star等图标类:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
4. 调整HTML中script标签位置
将<script>标签从<table>内部移出,放到{% block content %}末尾,避免破坏表格结构:
{% block content %} <h1 align="center"> Book Detail </h1> <table align="center" border="2" width="400"> <!-- 原有表格内容保持不变 --> </table> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> {% endblock content %}
验证步骤
- 重启Django开发服务器
- 清空浏览器缓存后刷新页面
- 打开浏览器开发者工具「网络」标签,确认
main.css和Font Awesome CSS已成功加载 - 查看「元素」标签,确认星级评分DOM元素已正确应用CSS样式
内容的提问来源于stack exchange,提问作者Scels12
相关产品推荐
相关产品推荐

