You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django项目中CSS媒体查询失效问题求助

解决Django项目中CSS媒体查询不生效的问题

1. 修复模板继承的结构错误

你的index.html模板写法存在关键问题:{% extends 'base.html' %}必须作为模板的第一行代码,且子模板不应重复定义<html>、<head>标签——这些结构应该由父模板base.html提供,子模板只需在对应block中填充内容。错误的HTML结构会导致浏览器解析异常,viewport标签无法正常生效,直接引发媒体查询失效。

修改后的index.html示例:

{% extends 'base.html' %}
{% load static %}

{% block head %}
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Oppapp</title>
    <link rel="stylesheet" href="{% static 'style.css' %}">
{% endblock head %}

{% block content %}
<div class="container">
    {% for object in object_list %}
    <div class="postlist">
        <div class="listicon">
            <img src="{{object.image.url}}">
        </div>
        <div class="listtext">
            <ol><a href="{{object.get_absolute_url}}">{{object.title}}</a></ol>
            <ol>{{object.article | truncatewords:15| linebreaks}}</ol>
            <ol>{{object.location}}</ol>
            <ol><small>{{object.created}}</small></ol>
        </div>
    </div>
    {% empty %}
    <p>No News Here</p>
    {% endfor %}
</div>
{% endblock content %}

同时确保base.html中定义了对应block:

<!DOCTYPE html>
<html lang="en">
<head>
    {% block head %}{% endblock head %}
</head>
<body>
    {% block content %}{% endblock content %}
</body>
</html>

2. 优化CSS媒体查询代码

媒体查询无需重复写入.postlist的全部样式,仅需覆盖需要修改的属性即可,避免冗余同时降低优先级冲突概率:

.postlist{
    border-radius: 5px;
    background-color: rgb(255, 255, 255);
    box-shadow: 0 0 5px hsl(208, 11%, 55%);
    margin-top: 20px;
    padding: 20px;
    display: flex;
    flex-direction: row;
    margin-bottom: 10px;
}
.listicon{
    display: flex;
    flex: 16%;
}
.listicon img{
    height: 180px;
    width: 180px;
}
.listtext{
    flex: 70%;
}

@media screen and (max-width:375px) {
    .postlist{
        flex-direction: column;
    }
    /* 移动端适配图片宽度,避免超出屏幕 */
    .listicon img{
        width: 100%;
        height: auto;
    }
}

3. 验证静态文件加载状态

打开浏览器开发者工具(F12),切换到Network标签,刷新页面后查看style.css是否成功加载(状态码为200),同时确认CSS内容中包含媒体查询代码。若未加载成功,检查settings.py静态文件配置,生产环境需运行python manage.py collectstatic,开发环境确保DEBUG模式下静态文件服务正常。

4. 检查浏览器缩放比例

确保浏览器缩放比例为100%,缩放会改变实际视口宽度,导致媒体查询的触发条件与预期不符。

内容的提问来源于stack exchange,提问作者oriohac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 17:01:25