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

Sass嵌套样式不生效求助:移除:nth-of-type(1)则恢复正常

解决Sass嵌套结合:nth-of-type(1)样式不生效的问题

我一眼就揪出了问题的核心——你在.shop-sec:nth-of-type(1)的规则里写了一个无效的CSS属性声明,这直接导致浏览器跳过了整个规则块里的所有样式,包括你嵌套的那些子元素样式。

问题根源

你的Sass代码里这一行是关键错误:

height: 500px auto;

CSS的height属性只接受单个有效值(比如固定长度、百分比、auto等),同时写500px和auto完全不符合语法规范。浏览器遇到这种无效声明时,会直接忽略整个包含它的规则块,哪怕后面的嵌套选择器逻辑完全正确,也不会被应用。

解决方案

  1. 先修正height属性的写法,根据你的需求二选一:

    • 若需要固定高度:height: 500px;
    • 若需要自适应高度:height: auto;
  2. 修正后的完整Sass代码(同时优化了嵌套结构的可读性):

.shop-sec:nth-of-type(1) { 
  height: 500px; /* 修正这里的无效属性 */
  background-color: white; 
  margin-top: 75px; 
  display: grid; 
  position: relative; 
  grid-template-columns: .75fr 1.25fr 1.25fr .75fr; 
  grid-gap: 15px; 

  .shop-sec-content { 
    width: 100%; 
    height: 100%; 

    img { 
      width: 100%; 
      height: auto; 
    }
  } 

  .shop-sec-content:nth-of-type(1) { 
    position: relative; 

    .shop-sec-text { 
      position: absolute; 
      right: 0; 
      padding-right: 50px; 
      transform: rotate(-90deg); 
      top: 42.5%; 
      font-size: 20px; 
      font-weight: bold; 
    }
  } 

  .shop-sec-content:nth-of-type(4) { 
    position: relative; 

    .shop-sec-text { 
      position: absolute; 
      left: 0; 
      padding-left: 50px; 
      top: 42.5%; 
      font-size: 20px; 
      font-weight: bold; 
    }
  } 

  .shop-sec-content:nth-of-type(2) { 
    position: relative; 

    .shop-sec-content-text { 
      position: absolute; 
      top: 50%; 
      margin-left: 50px; 
      font-size: 16px; 
      padding: 5px 20px; 
      color: white; 
      background-color: rgba(0, 0, 0, 0.507); 
      text-transform: uppercase; 
      letter-spacing: 5px; 

      span { 
        font-size: 24px; 
        font-weight: bold; 
        letter-spacing: 0px; 
      }
    }
  } 
}

额外验证点

如果修正后仍有问题,可以检查这两点:

  • 确认你的HTML中.shop-sec是它父元素下的第一个同类型元素(nth-of-type(1)匹配的是父元素下第一个<div>类型元素,若父元素里还有其他<div>在.shop-sec前面,这个选择器就不会匹配)。
  • 打开浏览器开发者工具(F12),查看Elements面板里的.shop-sec元素,检查是否有优先级更高的样式覆盖了你的规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:52:27