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

@media小屏幕样式失效求助:.test类未按预期切换样式

解决媒体查询中.test类样式不生效的问题

问题根源在于CSS的层叠顺序规则:你写在媒体查询中的.test选择器,和后面全局的.test选择器优先级完全相同,但因为全局的.test样式定义在媒体查询之后,所以无论屏幕尺寸如何,后面的样式都会覆盖媒体查询里的规则。而body样式能正常切换,是因为媒体查询里的body样式写在全局body样式之后,小屏时会覆盖大屏的body规则。

下面给出两种可行的解决方案:

方案1:调整CSS代码顺序(推荐)

将媒体查询块移动到全局.test样式的后面,这样小屏触发媒体查询时,里面的.test样式会覆盖全局的.test规则:

* {
    box-sizing: border-box;
}

body {
    background-color: rgb(169, 223, 242);
}

.test {
    color: blue;
    background-color: red;
}

@media all and (max-width: 56.25em) {
    body {
        background-color: red;
    }

    .test {
        color: green;
        background-color: yellow;
    }
}

.box-txt {
    text-align: center;
    color: whitesmoke;
}

方案2:提高媒体查询中选择器的优先级

通过增加选择器的特异性,让媒体查询里的.test规则优先级高于全局的.test,比如添加父元素选择器:

* {
    box-sizing: border-box;
}

body {
    background-color: rgb(169, 223, 242);
}

@media all and (max-width: 56.25em) {
    body {
        background-color: red;
    }

    body .test { /* 增加父元素选择器提升优先级 */
        color: green;
        background-color: yellow;
    }
}

.test {
    color: blue;
    background-color: red;
}

.box-txt {
    text-align: center;
    color: whitesmoke;
}

也可以临时使用!important(不推荐长期滥用,会增加后续样式维护难度):

@media all and (max-width: 56.25em) {
    body {
        background-color: red;
    }

    .test {
        color: green !important;
        background-color: yellow !important;
    }
}

优先选择方案1,遵循CSS正常的层叠顺序,更利于后续代码维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 13:48:22