Sass @extend Rule

The @extend rule allows for one selector to inherit the styles of another. This gives developers the ability to write a single base style that can be shared among multiples selectors.

Imagine creating custom buttons styles for a web site. The base button style would be the same for all to the buttons, only the background and border colors would change across the different custom buttons. In this situation, a base class could be used .btn and then additional modifier class .btn-cool or .btn-hot as shown below.

.btn {
  display: inline-block;
	padding: 6px 12px;
	text-align: center;
	white-space: nowrap;
	vertical-align: middle;
	cursor: pointer;
	border: none;
	border-radius: 4px;
	font-family: 1rem;
	user-select: none;
  color: #EEE8D6;
}

.btn-base {
  background-color: #022933;
}

.btn-hot {
  background-color: #D14348;
}

.btn-cool {
  background-color: #0076A3;
}

However, this method requires two classes to be added to each button. But, with the @extend rule, we include the base button styles in each of the custom buttons, eliminating the need to attach the .btn class to the buttons.

Furthermore, if we use a placeholder selector there is no need for .btn class at all.

$color-btn-default: #022933;
$color-btn-hot: #D14348;
$color-btn-cool: #0076A3;

%btn {
	display: inline-block;
	padding: 6px 12px;
	text-align: center;
	white-space: nowrap;
	vertical-align: middle;
	cursor: pointer;
	border: none;
	border-radius: 4px;
	font-family: 1rem;
	user-select: none;
	color: #EEE8D6;
}

.btn-default {
	@extend %btn;
	background: $color-btn-default;
}

.btn-hot {
	@extend %btn;
	background: $color-btn-hot;
}

.btn-cool {
	@extend %btn;
	background: $color-btn-cool;
}

The above SCSS would be compiled to the following CSS.

.btn-default, .btn-hot, .btn-cool {
  display: inline-block;
  padding: 6px 12px;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  cursor: pointer;
  border: none;
  border-radius: 4px;
  font-family: 1rem;
  user-select: none;
  color: #EEE8D6;
}

.btn-default {
  background: #022933;
}

.btn-hot {
  background: #D14348;
}

.btn-cool {
  background: #0076A3;
}