[SCSS] Reuse Styles with the SCSS @extend Directive

本文探讨了SCSS中@extend与@mixin指令的不同之处,包括它们如何改变源代码顺序、维护元素间的关系、继承特性、接受参数等方面的能力。此外,还通过示例展示了如何使用这些指令来编写可复用的样式。

We can write reusable styles with the SCSS @extend or @mixin directives. Which one is better? It depends. A better question is, how do they differ?
Extends:
change the source order, mixins don’t.
maintain relationships, mixins don’t.
share inherited traits, mixins don’t.
can extend multiple classes, mixins don’t.
can create multiple class declarations in the compiled CSS, mixins don’t.
can use the placeholder selector, mixins don’t.

Mixins:
can accept arguments, extends don’t.
can pass additional content, extends don’t.
repeat code when compiled, extends group class names together.
work well wIth media queries, extends have a limited interaction wIth media queries.

In this lesson we learn about writing reusable styles with the @extend directive and how it compares to the @mixin directive.

 

.base {
  color: red;

  &:hover {color: green}
  &::after {content: "?"}

  &-stuff {height: 5rem} // this will not be extended
}

.cool {height: 20rem}

.new {
  width: 20px;
  // extend multi classes
  @extend .base, .cool;
}

/*
 It is possible to use placeholder
*/

%base {
  color: red;
}

.new2 {
  @extend %base;
}

/*
  Placeholder for extend with mixin
*/
%hero {background: linear-gradient(red, white, black)}
%villain {background: darkred}

@mixin character($type: hero) {
  height: 20px;
  width: 20px;

  @extend %#{$type} // #{} --> output a string
}

.doc-ock {@include character(villain)}


/*
  Works with media query
*/
@media screen and (min-width: 800px) {
  %buddy { color: purple; }
}

@media screen and (min-width: 800px) {
  .buddy {
    @extend %buddy;
  }
}

 

Reference to http://sass-lang.com/documentation/file.SASS_REFERENCE.html#interpolation_

转载于:https://www.cnblogs.com/Answer1215/p/6799442.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值