【问题标题】:Include style one CSS class to another将样式包含一个 CSS 类到另一个
【发布时间】:2016-05-15 14:57:09
【问题描述】:

是否可以将一个 CSS 类的样式包含到另一个 CSS 类中?我的意思是 SASS @extends 几乎做了类似的事情,但它也设置了扩展类的样式,这不是必需的。见例子:

<style>
.myclass1{
  background:red;
}

.myclass2{
  color:blue;
  @extend .myclass1;
}
</style>

<div>
  <p class="myclass2">Hello i am class 2, my text is blue and background is red</p>
</div>

<div>
  <p class="myclass1">Hello i am class 1, my text should not blue and my background is red</p>
</div>

发布的示例受到CSS-tricks Web 文章的启发,但这里的一切都非常混乱,它没有按应有的方式工作。 myclass2 应该根据文章给出 myclass1。但是,它给出了奇怪的输出。我是否朝着正确的方向前进?还是文章有误?

更新: 问题只是关于SAAS的@extend背后的实际概念,以及将其他CSS类包含到另一个,有什么区别?

【问题讨论】:

  • 似乎在代码 sn-p 中工作正常?
  • ...您仍然需要编译 SASS 才能使 @extend 工作。
  • 从链接到的文章中:所有三个最流行的 CSS 预处理器都支持扩展。您没有使用任何预处理器,而是试图将其视为 CSS,但事实并非如此。
  • 如果你不想使用预处理器,你可以使用 PostCSS 和 github.com/jonathantneal/postcss-sass-extend 否则你需要使用预处理器

标签: html css extends saas


【解决方案1】:

SASS 是一个 CSS 预处理器,基本上意味着 SASS 语法被编译成纯 CSS。 SASS 提供的功能,例如 @extend 以及使用 $ 语法建立变量等,只能使用 SASS(CSS3 无法实现)

话虽如此,您只需将类链接在一起即可在常规 CSS 中实现 SASS 的 @extend 功能的结果:

.blue, .green {
 <your css here>
}

【讨论】:

    【解决方案2】:

    您可以使用逗号来匹配多个选择器:

    .myclass1, .myclass2 {
      background: red;
    }
    .myclass2 {
      color: blue;
    }
    <p class="myclass2">Hello i am class 2, my text is blue and background is red</p>
    <p class="myclass1">Hello i am class 1, my text should not blue and my background is red</p>

    【讨论】:

      【解决方案3】:

      没有预处理器的 CSS(SASS、LESS 等):

      .myclass1{
      	background:red;
      }
      
      .myclass2{
      	color:blue;
      }
      <div>
      <p class="myclass1 myclass2">Hello, I am of class 2 (my text is blue) and of class 1 (my background is red)</p>
      </div>
      
      <div>
      <p class="myclass1">Hello, I am only of class 1 (my background is red)</p>
      </div>

      您可以将多个类添加到同一个元素。

      【讨论】:

        猜你喜欢
        • 2014-04-23
        • 2016-09-30
        • 2011-03-03
        • 2020-12-03
        • 1970-01-01
        • 2010-11-15
        • 2023-03-26
        • 2018-11-04
        • 2011-10-27
        相关资源
        最近更新 更多