html - SASS:检查元素类型内部的元素类型

标签 html css sass

是否可以检查元素类型 内部 元素类型? 这对我来说似乎是一个常见问题,但我无法在 Stack Overflow 上找到它。

例如:

h1, h2, h3, h4 {
    margin-top: 20px;
    margin-bottom: 20px;
    color: red;

    & h2 {
        margin-top: 0;
    }
}

我知道同样的事情适用于像这样的类:

.test,
.test-two {
     color: red;

     &.test {
         color: blue;
     }
}

在这种情况下,我可以在父类中覆盖 .test。 同样的事情不适用于上面示例中的元素类型。

PS:我并不是要修复这个 HTML(这只是一个示例),而是要找到一种嵌套元素类型的方法。

提前致谢!

最佳答案

您在此处所写的内容并不是实现听起来您正在尝试做的事情的好方法。在您的第一个片段中:

.test,
.test-two {
     /* ... Other shared styles ... */
     color: red;

     &.test {
         color: blue;
     }
}

这听起来像是您要尝试做的是在设置了它与不同选择器共享的一些其他属性后覆盖 test 类的颜色。但是,考虑一下您编写的内容将编译为:

.test,
.test-two {
    color: red;
}

.test.test,
.test-two.test {
    color: blue;
}

所以,现在你有一个复合类选择器,上面有两个相同的类,这是不必要的。然后这里还有另一个选择器,您很可能甚至不需要。您希望避免添加不必要的特殊性和输出无效或无用的代码。在此示例中,编译后您应该希望看到的 CSS 是这样的:

.test,
.test-two {
    /* ... Other shared styles ... */
    color: red;
}

.test {
    color: blue;
}

不错的低特异性选择器利用级联中的选择器优先级。在 SCSS 中,您只需编写完全相同的内容即可。尝试将其表述为嵌套选择器确实没有任何好处,因为这样做会产生更糟糕的代码,或者不必要地令人费解。但是,如果出于某种原因您觉得该部分需要嵌套,一个简单的方法是使用 @at-root。像这样:

.test,
.test-two {
    color: red;

    @at-root {
        .test {
            color: blue;
        }
    }
}

你可以去the documentation for @at-root如果您想了解更多相关信息。

这让我明白了你问题的实质。同样,您想要覆盖样式的主要方式是使用选择器优先级,而不是开始使用不断增加的特异性级别,这会使代码变得过于复杂和庞大,导致过度使用 !important,并且引发了一场特异性选择器 war ,导致不必要的长选择器性能不佳。

所以在这段代码中:

h1, h2, h3, h4 {
    margin-top: 20px;
    margin-bottom: 20px;
    color: red;

    & h2 {
        margin-top: 0;
    }
}

如果您要做的只是覆盖 h2 样式,那么您应该希望在编译后看到的 CSS 是这样的:

h1, h2, h3, h4 {
    margin-top: 20px;
    margin-bottom: 20px;
    color: red;
}

h2 {
    margin-top: 0;
}

但是,您当前正在执行的操作在编译后看起来像这样:

h1, h2, h3, h4 {
    margin-top: 20px;
    margin-bottom: 20px;
    color: red;
}

h1 h2,
h2 h2,
h3 h2,
h4 h2 {
    margin-top: 0;
}

就像在第一个示例中一样,可能没有充分的理由像这样嵌套这些选择器。要么这样做(与所需的 CSS 输出相同):

h1, h2, h3, h4 {
    margin-top: 20px;
    margin-bottom: 20px;
    color: red;
}

h2 {
    margin-top: 0;
}

或者如果你坚持使用嵌套,你可以像我在第一个例子中那样使用@at-root:

h1, h2, h3, h4 {
    margin-top: 20px;
    margin-bottom: 20px;
    color: red;
    
    @at-root {
        h2 {
            margin-top: 0;
        }
    }
}

希望这对您有所帮助。如果我偏离了您期望的目标,如果您提供更多详细信息,我很乐意修改我的答案。

关于html - SASS:检查元素类型内部的元素类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51554841/

相关文章:

javascript - 为什么 scroll-snap 在 CSS 中不起作用?

javascript - 用 Canvas 绘制 Javascript

html - 如何与 li last-child 在同一行中创建水平线

javascript - 使用 CSS - ExtJs 进行鼠标悬停时如何更改面板上的图像?

css - SASS :after :hover selector

sass - 有没有办法结合 scss 嵌套和 tailwindcss?

html - 在 <head> 元素之外使用 &lt;style&gt; 标签是否正确?

html - 是否可以为 html 电子邮件创建垂直文本方向?

使用包含时,带有 margin-left 的 jQuery 可拖动元素不会向左移动

html:有没有办法在html代码中包含滚动条