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

Sass中如何通过媒体查询修改伪元素before/after的宽度

解决Sass媒体查询修改伪元素样式无效的问题

你的问题出在媒体查询里错误嵌套了span选择器——当前代码已经在span的规则块内,再写span会让编译后的CSS变成span span::before,而页面中不存在这种嵌套结构,所以伪元素样式根本匹配不到目标元素。

修正后的代码

span {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1rem;
  position: relative;
  color: $grey2;

  &::before {
    content: "   ";
    height: 2px;
    background: $grey1;
    width: 38%;
    position: absolute;
    left: 0;
  }
  &::after {
    content: "";
    height: 2px;
    background: $grey1;
    width: 38%;
    position: absolute;
    right: 0;
  }

  @media only screen and (max-width: 700px) {
    background: red;
    // 直接修改当前span的伪元素,无需再嵌套span
    &::before {
      width: 10%;
      // 其他重复样式可省略,继承父规则即可
    }
    &::after {
      width: 10%;
    }
  }
}

关键说明

  • 媒体查询写在span规则块内时,&代表当前的span选择器,&::before等价于span::before,能正确匹配目标伪元素。
  • 无需重复定义display、position等父规则已有的样式,仅修改需要调整的width即可,代码更简洁高效。

内容的提问来源于stack exchange,提问作者Noc er Gal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 17:16:28