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

CSS选择器优先级正确仍需添加!important才能生效是什么原因

问题根因

你必须加!important才能生效的核心原因是移动端媒体查询内的选择器优先级低于桌面端的同规则选择器:

  • 桌面端编译后的.section--hasImage选择器为 .section .section__content.section--hasImage,包含3个类选择器,权重为30
  • 移动端编译后的同规则选择器为 section > .section__content.section--hasImage,包含1个标签选择器+2个类选择器,权重仅为21
    相同规则下低优先级样式无法覆盖高优先级样式,因此你只能靠!important强制提升优先级生效。

修复方案

只需把移动端媒体查询里的section > .section__content改为.section > .section__content,此时选择器权重变为30,和桌面端规则权重一致,且代码书写顺序靠后,无需加!important就能自然覆盖桌面端样式。

代码优化建议

  • 移除无意义的clamp极值:比如h1的上限2000px、p的上限1800px、移动端内容宽度下限10px完全没有实际使用场景,替换为符合你设计规范的合理值即可,避免超大/超小屏幕下样式异常
  • 行高统一使用无单位数值:把p标签的line-height: 120%改为line-height: 1.2,避免样式继承时出现意外问题
  • 移除不必要的!important,修复优先级问题后不需要额外强制覆盖

优化后完整代码

// Content
.section {
  padding: clamp(50px, 5vh, 200px) 0;

  .section__content {
    width: clamp(300px, 60vw, 100vw);
    margin: 0 auto;

    h2 {
      font-family: $ff-header;
      font-size: clamp(24px, 1.1vw + 1rem, 50px);
      margin-bottom: 1.3rem;
      line-height: 1;
    }

    p {
      font-family: $ff-content;
      font-size: 1rem;
      line-height: 1.2;
    }

    &.section--hasImage {
      display: flex;
      gap: 2rem;
      justify-content: space-between;
      align-items: center;

      .col {
        width: 45%;
      }
    }
  }
}

// Breakpoints
@media (max-width: 50em) {
  .hero {
    justify-content: center;

    .hero__content {
      text-align: center;
      margin: 0;

      h1 {
        // 可替换为你实际需要的最大字号
        font-size: clamp(30px, 10vw + 1rem, 80px);
      }

      p {
        // 可替换为你实际需要的最大字号
        font-size: clamp(16px, 1vw + 1rem, 28px);
      }
    }
  }

  .section > .section__content {
    width: clamp(300px, 85vw, 85vw);

    &.section--hasImage {
      display: block;

      .col {
        width: 100%;

        &:last-of-type {
          margin-top: 2rem;
        }
      }
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 18:45:06