当前位置:  首页>> 技术小册>> SASS零基础入门

@extend 指令告诉 Sass 一个选择器的样式从另一选择器继承。

如果一个样式与另外一个样式几乎相同,只有少量的区别,则使用 @extend 就显得很有用。

以下 Sass 实例中,我们创建了一个基本的按钮样式 .button-basic,接着我们定义了两个按钮样式 .button-report 与 .button-submit,它们都继承了 .button-basic ,它们主要区别在于背景颜色与字体颜色,其他的样式都是一样的。

Sass 代码:

  1. .button-basic {
  2. border: none;
  3. padding: 15px 30px;
  4. text-align: center;
  5. font-size: 16px;
  6. cursor: pointer;
  7. }
  8. .button-report {
  9. @extend .button-basic;
  10. background-color: red;
  11. }
  12. .button-submit {
  13. @extend .button-basic;
  14. background-color: green;
  15. color: white;
  16. }

将以上代码转换为 CSS 代码,如下所示:

Css 代码:

  1. .button-basic, .button-report, .button-submit {
  2. border: none;
  3. padding: 15px 30px;
  4. text-align: center;
  5. font-size: 16px;
  6. cursor: pointer;
  7. }
  8. .button-report {
  9. background-color: red;
  10. }
  11. .button-submit {
  12. background-color: green;
  13. color: white;
  14. }

使用 @extend 后,我们在 HTML 按钮标签中就不需要指定多个类 class=”button-basic button-report” ,只需要设置 class=”button-report” 类就好了。

@extend 很好的体现了代码的复用。


该分类下的相关小册推荐:

暂无相关推荐.