如何通过@media在992px宽度下将CSS背景图替换为纯色背景?
正确实现方法
你的问题出在媒体查询的语法错误——不能把@media写在CSS属性值里,它需要作为独立的代码块来包裹要修改的样式。另外,原代码里background:url(...)会覆盖background-color(因为background是简写属性),所以要在媒体查询里明确覆盖背景图设置。
正确的完整代码:
/* 基础样式(所有屏幕通用) */ .herogirl{ position:relative; width:100vw; height:70vh; display:flex; justify-content:left; align-items:center } .herogirl::before{ content:""; position:absolute; top:0; left:0; width:100%; height:100%; background:url(/templates/assets/img/hero-header-lady.jpg); background-color: #b7b5b8; background-repeat:no-repeat; background-size:cover; background-position:center center; filter:brightness(100%); border-radius:5px } /* 屏幕宽度≥992px时的样式 */ @media screen and (min-width: 992px) { .herogirl::before { /* 用background简写直接设置纯色,覆盖原有背景图 */ background: #b7b5b8; /* 如果需要保留其他background属性,也可以只去掉背景图: background-image: none; */ } }
关键说明:
- 媒体查询
@media必须作为独立块存在,不能嵌套在单个选择器的属性里。 - 因为
background:url(...)是简写属性,优先级高于单独的background-color,所以要在媒体查询里用background: #b7b5b8直接覆盖,或者设置background-image: none让原来的background-color生效。
内容的提问来源于stack exchange,提问作者Charley Y.
相关产品推荐
相关产品推荐

