Extending vs Mixing in Sass: Style Reuse Comparison
📖 Scenario: You are creating a simple webpage with two types of buttons: a primary button and a secondary button. Both buttons share some common styles like padding and font size, but differ in background color and border. You want to reuse the common styles efficiently using Sass.
🎯 Goal: Build Sass code that shows how to reuse common button styles using extend and mixins. You will create a base button style, then create a primary button by extending it, and a secondary button by including a mixin.
📋 What You'll Learn
Create a base button style with padding and font size
Create a primary button style that extends the base button style and adds a blue background
Create a mixin for the base button style
Create a secondary button style that includes the base button mixin and adds a gray background
💡 Why This Matters
🌍 Real World
Web developers often need to reuse styles for buttons or other UI elements to keep code clean and consistent.
💼 Career
Understanding Sass features like @extend and mixins is important for front-end developers to write maintainable and scalable CSS.
Progress0 / 4 steps
1
Create the base button style
Write a Sass style for a class .button-base that sets padding to 1rem 2rem and font-size to 1.2rem.
SASS
Hint
Use a class selector .button-base and add the two properties inside curly braces.
2
Create the primary button style using @extend
Write a Sass style for a class .button-primary that @extends .button-base and sets background-color to blue.
SASS
Hint
Use @extend .button-base; inside .button-primary and add the background color property.
3
Create a mixin for the base button style
Write a Sass mixin named button-base-style that sets padding to 1rem 2rem and font-size to 1.2rem.
SASS
Hint
Use @mixin button-base-style { ... } with the same properties as the base button.
4
Create the secondary button style using the mixin
Write a Sass style for a class .button-secondary that @includes the button-base-style mixin and sets background-color to gray.
SASS
Hint
Use @include button-base-style; inside .button-secondary and add the background color property.
Practice
(1/5)
1. What is the main difference between @extend and @mixin in Sass?
easy
A. @extend shares styles by combining selectors, @mixin copies styles into selectors.
B. @extend copies styles into selectors, @mixin combines selectors.
C. @extend creates new CSS files, @mixin deletes unused styles.
D. @extend is used only for variables, @mixin is used only for functions.
Solution
Step 1: Understand @extend behavior
@extend merges selectors that share the same styles, reducing CSS size by combining rules.
Step 2: Understand @mixin behavior
@mixin copies the style block wherever it is included, allowing flexible reuse but increasing CSS size.
Final Answer:
@extend shares styles by combining selectors, @mixin copies styles into selectors. -> Option A