【问题标题】:Is it possible to have a local class inherit all classes imported from a file?是否可以让本地类继承从文件导入的所有类?
【发布时间】:2019-02-02 13:32:44
【问题描述】:

假设我有一个看起来像这样的 css 文件:

/* Base styles */
.content {
    background-color: var(--background);
    color: var(--text);
    font-family: "Helvetica Neue", Helvetica, sans-serif;
    font-size: 16px;
    line-height: 1.5;
    text-rendering: optimizeLegibility;
}

@media (min-width: 500px) {
    .content {
        font-size: 22px;
    }
}

/* Headers */
h2 {
    font-family: "Helvetica Neue", Helvetica, sans-serif;
    font-size: 24px;
    font-weight: 700;
}

/* Classes */
.small-caps {
    font-feature-settings: "tnum";
    letter-spacing: 0.05em;
}

使用 PostCSS,您可以像这样使用另一个类的属性:

.another-class {
    composes: content from "other-file.css";
}

... 将被编译为:

.another-class {
    background-color: var(--background);
    color: var(--text);
    font-family: "Helvetica Neue", Helvetica, sans-serif;
    font-size: 16px;
    line-height: 1.5;
    text-rendering: optimizeLegibility;
}

是否可以让一个类从给定目标继承 所有 样式,以便您可以编写类似(伪代码)的内容:

.another-class {
    composes: * from "other-file.css";
}

……渲染出来的效果是这样的?

/* Base styles */
.another-class .content {
    background-color: var(--background);
    color: var(--text);
    font-family: "Helvetica Neue", Helvetica, sans-serif;
    font-size: 16px;
    line-height: 1.5;
    text-rendering: optimizeLegibility;
}

@media (min-width: 500px) {
    .another-class .content {
        font-size: 22px;
    }
}

/* Headers */
.another-class h2 {
    font-family: "Helvetica Neue", Helvetica, sans-serif;
    font-size: 24px;
    font-weight: 700;
}

/* Classes */
.another-class .small-caps {
    font-feature-settings: "tnum";
    letter-spacing: 0.05em;
}

【问题讨论】:

标签: css webpack postcss css-modules


【解决方案1】:

这可以使用 Sass (Scss)。

例子:

test1.scss

.elem {
  background: red;
  @import 'test2';
}

test2.scss

.inner {
  background: blue;
}

.outer {
  background: green;
}

@media (max-width: 500px){
  .something {
    color: black;
  }
}

输出:

.elem {
  background: red; }
  .elem .inner {
    background: blue; }
  .elem .outer {
    background: green; }
  @media (max-width: 500px) {
    .elem .something {
      color: black; } }

【讨论】:

  • 我的意思是包含一个“no sass”注释但没有,所以我打算将您的答案标记为已接受。谢谢你的回答!
【解决方案2】:

是的,这是可能的。您可以像使用 css 一样使用 SASS 来实现这一点。

.error {
  border: 1px #f00;
  background-color: #fdd;
}
.seriousError {
  border-width: 3px;
}

你可以像这样使用它

.error {
  border: 1px #f00;
  background-color: #fdd;
}
.seriousError {
  @extend .error;
  border-width: 3px;
}

@extend 指令通过告诉 Sass 一个选择器应该继承另一个选择器的样式来避免这些问题。

详情请咨询SASS documentation

【讨论】:

    猜你喜欢
    • 2021-09-25
    • 1970-01-01
    • 2012-05-22
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 2014-02-13
    • 2016-01-26
    相关资源
    最近更新 更多