Performance: Why mixins eliminate duplication
This affects CSS file size and browser style recalculation by reducing repeated code blocks.
@mixin common-padding { padding: 1rem 2rem; border-radius: 0.5rem; } @media (min-width: 600px) { .btn { @include common-padding; } } .card { @include common-padding; }
@media (min-width: 600px) { .btn { padding: 1rem 2rem; border-radius: 0.5rem; } } .card { padding: 1rem 2rem; border-radius: 0.5rem; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Repeated CSS blocks | No extra DOM nodes | Multiple style recalculations | Higher paint cost due to slower style calculation | [X] Bad |
| Using mixins for reuse | No extra DOM nodes | Single style recalculation per unique rule | Lower paint cost due to efficient style calculation | [OK] Good |
@mixin.@mixin name { ... }. Other options use incorrect keywords.@mixin border-radius($radius) {
border-radius: $radius;
}
.box {
@include border-radius(10px);
background: blue;
}border-radius takes a parameter $radius and sets border-radius property..box includes the mixin with argument 10px, so border-radius: 10px; is added.@mixin text-style {
font-size: 16px;
color: black;
}
.title {
text-style;
font-weight: bold;
}@include mixin-name; inside selectors.text-style; without @include, so it won't apply the mixin styles.@mixin button-style($bg-color) {
background-color: $bg-color;
padding: 1rem 2rem;
border-radius: 0.5rem;
}
.primary-btn {
@include button-style(blue);
}
.secondary-btn {
@include button-style(gray);
}button-style defines padding and border-radius once and accepts a background color parameter..primary-btn and .secondary-btn include the mixin with different colors, reusing common styles without duplication.Pass the test and this pattern moves unknown