Bird
Raised Fist0
SASSmarkup~15 mins

Grid system mixin from scratch in SASS - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Grid system mixin from scratch
What is it?
A grid system mixin in Sass is a reusable piece of code that helps you create flexible, organized layouts using rows and columns. It simplifies placing elements on a page by dividing the space into equal parts, like slices of a cake. This mixin lets you control how wide each column is and how they stack on different screen sizes. It makes building responsive designs easier and cleaner.
Why it matters
Without a grid system mixin, developers would write repetitive CSS for every layout, making code messy and hard to maintain. It solves the problem of consistent spacing and alignment across a website, especially when the design needs to adapt to different screen sizes. This means users get a better experience on phones, tablets, and desktops, and developers save time and avoid mistakes.
Where it fits
Before learning grid system mixins, you should understand basic CSS layout concepts like block and inline elements, and how CSS properties like width and margin work. After mastering grid mixins, you can explore advanced responsive design techniques, CSS Grid and Flexbox frameworks, and component-based styling in frameworks like React or Vue.
Mental Model
Core Idea
A grid system mixin breaks a page into equal columns and lets you easily place content by specifying how many columns it should span.
Think of it like...
Imagine a chocolate bar divided into equal squares. You can eat one square, two squares, or more, depending on your hunger. The grid system is like that chocolate bar, and the mixin helps you pick how many squares your content takes.
┌─────────────┬─────────────┬─────────────┬─────────────┐
│ Column 1    │ Column 2    │ Column 3    │ Column 4    │
├─────────────┼─────────────┼─────────────┼─────────────┤
│ Content spans│ Content spans│ Empty space │ Empty space │
│ 2 columns   │ 1 column    │             │             │
└─────────────┴─────────────┴─────────────┴─────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding basic grid concepts
🤔
Concept: Learn what a grid system is and why columns matter in layout design.
A grid system divides a page horizontally into equal parts called columns. Each column can hold content. By combining columns, you control how wide an element is. For example, in a 12-column grid, an element spanning 6 columns takes half the width. This helps keep layouts balanced and consistent.
Result
You understand that grids split space into columns and that elements can span multiple columns to control width.
Understanding the division of space into columns is the foundation for building flexible and consistent layouts.
2
FoundationBasics of Sass mixins
🤔
Concept: Learn how to write and use mixins in Sass to reuse CSS code.
A mixin in Sass is like a recipe you write once and use many times. It can take inputs (parameters) and output CSS styles. For example, you can write a mixin to set padding and call it wherever you want consistent spacing. This saves time and keeps code clean.
Result
You can create simple mixins and include them in your stylesheets to avoid repeating code.
Knowing how mixins work lets you build reusable layout helpers like grid systems efficiently.
3
IntermediateCreating a basic grid mixin
🤔Before reading on: do you think the mixin should calculate width based on total columns or fixed pixel values? Commit to your answer.
Concept: Write a mixin that calculates column width based on total columns and the number of columns to span.
@mixin grid-column($span, $total-columns: 12) { width: (100% / $total-columns) * $span; float: left; box-sizing: border-box; padding: 0 0.5rem; } This mixin takes how many columns an element should span and the total columns in the grid (default 12). It calculates the width as a percentage and floats the element left to align columns side by side.
Result
Elements using this mixin will have widths proportional to the columns they span, aligning horizontally.
Calculating widths as percentages based on total columns makes the grid flexible and responsive to container size.
4
IntermediateAdding gutters and spacing control
🤔Before reading on: do you think gutters should be part of the width calculation or separate padding/margin? Commit to your answer.
Concept: Improve the mixin to include gutters (space between columns) without breaking the layout.
Gutters are spaces between columns. Instead of adding gutters inside width, we add horizontal padding inside columns and negative margin on the row container to keep alignment. @mixin grid-row { margin-left: -0.5rem; margin-right: -0.5rem; overflow: hidden; } @mixin grid-column($span, $total-columns: 12) { width: (100% / $total-columns) * $span; float: left; box-sizing: border-box; padding-left: 0.5rem; padding-right: 0.5rem; } This keeps gutters consistent and columns aligned.
Result
Columns have space between them without causing layout overflow or misalignment.
Separating gutters from width calculation prevents layout breaking and keeps spacing consistent.
5
IntermediateMaking the grid responsive with media queries
🤔Before reading on: do you think the mixin should handle responsiveness internally or rely on external media queries? Commit to your answer.
Concept: Add responsiveness by changing column spans on different screen sizes using media queries inside the mixin or alongside it.
You can write media queries to adjust column spans for smaller screens. For example: @include grid-column(12) { // full width on small screens @media (min-width: 768px) { @include grid-column(6); // half width on tablets and up } } Alternatively, create mixins for breakpoints to reuse. @mixin respond-to($breakpoint) { @if $breakpoint == tablet { @media (min-width: 768px) { @content; } } } This approach keeps the grid flexible across devices.
Result
Layouts adapt to screen size, stacking columns on small screens and aligning side by side on larger ones.
Integrating media queries with grid mixins enables responsive designs that work well on all devices.
6
AdvancedHandling nested grids and clearing floats
🤔Before reading on: do you think nested grids require new mixins or just reuse existing ones? Commit to your answer.
Concept: Learn how to nest grids inside columns and clear floats to prevent layout issues.
Nested grids are grids inside a grid column. Use the same grid-row and grid-column mixins inside a column. To prevent float collapse, clear floats after rows: .grid-row::after { content: ''; display: table; clear: both; } This ensures nested grids behave correctly and the parent container wraps its floated children.
Result
Nested grids display properly without collapsing or overlapping content.
Clearing floats and reusing mixins for nested grids maintains layout integrity in complex designs.
7
ExpertOptimizing grid mixins for performance and flexibility
🤔Before reading on: do you think using floats is still the best approach for grids today? Commit to your answer.
Concept: Explore modern alternatives and optimizations for grid mixins, including Flexbox and CSS Grid integration.
Floats were common for grids but have drawbacks like clearfix hacks. Modern CSS offers Flexbox and CSS Grid for layout. You can write mixins that use Flexbox: @mixin flex-grid-column($span, $total-columns: 12) { flex: 0 0 calc(100% / $total-columns * $span); max-width: calc(100% / $total-columns * $span); padding: 0 0.5rem; box-sizing: border-box; } This approach simplifies layout, removes float issues, and improves responsiveness. Understanding when to use floats vs Flexbox or Grid is key for production-ready code.
Result
Grid mixins become more robust, easier to maintain, and compatible with modern CSS standards.
Knowing modern CSS layout methods helps you write better grid mixins and avoid legacy pitfalls.
Under the Hood
The grid mixin calculates widths as percentages based on the total number of columns and the span requested. It applies CSS properties like float or flex to align columns horizontally. Gutters are created by padding inside columns and negative margins on the row container to keep alignment. Media queries adjust these widths for responsiveness. Internally, the browser calculates layout by distributing available space according to these percentages and CSS rules.
Why designed this way?
Early web layouts used floats because CSS lacked flexible layout tools. The grid mixin abstracts float calculations to simplify layout creation. Gutters are separated from width to avoid breaking box models. Media queries are integrated to handle different screen sizes as mobile devices became common. Modern CSS features like Flexbox and Grid emerged later, offering better solutions, but the mixin approach remains useful for compatibility and gradual upgrades.
┌───────────────┐
│ Grid Container│
│ (row with    │
│ negative      │
│ margins)     │
└──────┬────────┘
       │ contains
┌──────▼────────┐
│ Grid Column   │
│ (width % +   │
│ padding for  │
│ gutters)     │
└──────────────┘
       │
       ▼
Browser calculates layout by distributing space based on widths and padding.
Myth Busters - 4 Common Misconceptions
Quick: Do you think grid columns must always add up exactly to total columns? Commit yes or no.
Common Belief:Grid columns must always add up exactly to the total number of columns in a row.
Tap to reveal reality
Reality:Columns can add up to less than or more than total columns; the layout will adjust but may cause wrapping or empty space.
Why it matters:Assuming columns must add up exactly can cause confusion and rigid layouts, preventing flexible designs where some rows have fewer columns.
Quick: Do you think gutters are included inside column widths? Commit yes or no.
Common Belief:Gutters are part of the column width and reduce the content space.
Tap to reveal reality
Reality:Gutters are created by padding inside columns and negative margins on the row, separate from width calculation, preserving content space.
Why it matters:Including gutters inside widths can cause layout overflow or misalignment, breaking the grid.
Quick: Do you think floats are the best way to build grids today? Commit yes or no.
Common Belief:Using floats is the best and only way to create grid layouts.
Tap to reveal reality
Reality:Modern CSS layout methods like Flexbox and Grid are better suited for grids, offering simpler and more powerful control.
Why it matters:Relying on floats can lead to complex hacks and harder maintenance, missing out on modern CSS benefits.
Quick: Do you think media queries inside mixins always make code cleaner? Commit yes or no.
Common Belief:Putting media queries inside grid mixins always improves code clarity and reuse.
Tap to reveal reality
Reality:Sometimes separating media queries from mixins keeps code more readable and flexible, especially for complex responsive designs.
Why it matters:Misusing media queries inside mixins can make debugging and customization harder.
Expert Zone
1
Grid gutters should be handled outside width calculations to avoid box-sizing issues and layout breaks.
2
Nested grids require careful float clearing or switching to Flexbox/Grid to prevent collapsing containers.
3
Mixins can accept parameters for total columns and gutter size to make grids highly customizable across projects.
When NOT to use
Avoid using float-based grid mixins for new projects where CSS Grid or Flexbox can be used directly. For complex layouts with overlapping or asymmetric columns, CSS Grid is more powerful. Use utility-first CSS frameworks like Tailwind CSS for faster development instead of custom mixins when appropriate.
Production Patterns
In production, grid mixins are often wrapped in component libraries or design systems to enforce consistent spacing and breakpoints. They are combined with responsive utilities and theming variables. Teams migrate gradually from float-based grids to Flexbox or CSS Grid, maintaining backward compatibility.
Connections
CSS Flexbox
Builds-on
Understanding grid mixins helps grasp Flexbox's flexible box model, which can replace floats for layout with simpler alignment and distribution.
Modular Design
Same pattern
Grid mixins embody modular design principles by encapsulating layout logic into reusable, parameterized units, improving maintainability.
Urban Planning
Analogy in structure
Just like city planners divide land into blocks and streets for organized growth, grid systems divide page space for orderly content placement.
Common Pitfalls
#1Columns overlap or break layout due to missing clearfix.
Wrong approach:.grid-row { margin-left: -0.5rem; margin-right: -0.5rem; } .grid-column { float: left; width: 50%; padding: 0 0.5rem; } /* Missing clearfix */
Correct approach:.grid-row { margin-left: -0.5rem; margin-right: -0.5rem; overflow: hidden; /* clearfix */ } .grid-column { float: left; width: 50%; padding: 0 0.5rem; }
Root cause:Forgetting to clear floats causes parent containers to collapse, breaking layout flow.
#2Gutters included inside width causing overflow.
Wrong approach:@mixin grid-column($span, $total-columns: 12) { width: ((100% / $total-columns) * $span) - 1rem; float: left; padding: 0 0.5rem; }
Correct approach:@mixin grid-column($span, $total-columns: 12) { width: (100% / $total-columns) * $span; float: left; padding: 0 0.5rem; }
Root cause:Subtracting gutter size from width causes miscalculation and layout overflow.
#3Hardcoding pixel widths instead of percentages.
Wrong approach:@mixin grid-column($span) { width: 100px * $span; float: left; }
Correct approach:@mixin grid-column($span, $total-columns: 12) { width: (100% / $total-columns) * $span; float: left; }
Root cause:Using fixed pixel widths breaks responsiveness and flexibility.
Key Takeaways
Grid system mixins in Sass help create flexible, reusable layouts by dividing space into columns and calculating widths dynamically.
Separating gutters from width calculations prevents layout breaks and keeps spacing consistent across devices.
Integrating media queries with grid mixins enables responsive designs that adapt smoothly to different screen sizes.
Modern CSS layout methods like Flexbox and Grid offer better alternatives to float-based grids, but understanding mixins builds a strong foundation.
Clearing floats and handling nested grids properly is essential to maintain layout integrity in complex designs.

Practice

(1/5)
1. What is the main purpose of a grid system mixin in Sass?
easy
A. To create flexible column layouts with reusable code
B. To add colors to text elements
C. To write JavaScript functions inside Sass
D. To load external fonts automatically

Solution

  1. Step 1: Understand the role of mixins in Sass

    Mixins let you reuse code blocks with parameters to customize styles.
  2. Step 2: Identify what a grid system mixin does

    A grid system mixin helps create column layouts that adapt easily by changing parameters.
  3. Final Answer:

    To create flexible column layouts with reusable code -> Option A
  4. Quick Check:

    Grid mixin = flexible columns [OK]
Hint: Grid mixins simplify layout by reusing column code [OK]
Common Mistakes:
  • Confusing mixins with variables
  • Thinking mixins add colors only
  • Assuming mixins run JavaScript
2. Which of the following is the correct way to define a simple grid mixin with columns and gap parameters in Sass?
easy
A. @mixin grid($columns, $gap) { display: flex; columns: $columns; gap: $gap; }
B. @mixin grid($columns, $gap) { display: block; grid-columns: $columns; grid-gap: $gap; }
C. @mixin grid($columns, $gap) { display: grid; grid-template-columns: repeat($columns, 1fr); gap: $gap; }
D. @mixin grid($columns, $gap) { display: grid; columns: $columns; gap: $gap; }

Solution

  1. Step 1: Check the display property for grid layout

    Grid layouts require display: grid;, not flex or block.
  2. Step 2: Verify grid-template-columns and gap syntax

    Using grid-template-columns: repeat($columns, 1fr); sets equal columns, and gap: $gap; sets spacing.
  3. Final Answer:

    @mixin grid($columns, $gap) { display: grid; grid-template-columns: repeat($columns, 1fr); gap: $gap; } -> Option C
  4. Quick Check:

    Grid needs display:grid and repeat() [OK]
Hint: Use display:grid and repeat() for columns [OK]
Common Mistakes:
  • Using display:flex instead of grid
  • Using incorrect property names like columns
  • Missing repeat() function for columns
3. Given this Sass mixin and usage:
@mixin grid($cols, $gap) {
  display: grid;
  grid-template-columns: repeat($cols, 1fr);
  gap: $gap;
}

.container {
  @include grid(3, 2rem);
}

What CSS will be generated for .container?
medium
A. .container { display: grid; grid-template-columns: repeat(3, 1fr); gap: 2rem; }
B. .container { display: flex; columns: 3; gap: 2rem; }
C. .container { display: grid; grid-template-columns: 3fr; gap: 2rem; }
D. .container { display: block; grid-template-columns: repeat(3, 1fr); gap: 2rem; }

Solution

  1. Step 1: Understand mixin parameters and usage

    The mixin sets grid display, columns with repeat, and gap using passed values 3 and 2rem.
  2. Step 2: Translate Sass mixin to CSS output

    Including the mixin with (3, 2rem) generates CSS with display: grid;, grid-template-columns: repeat(3, 1fr);, and gap: 2rem;.
  3. Final Answer:

    .container { display: grid; grid-template-columns: repeat(3, 1fr); gap: 2rem; } -> Option A
  4. Quick Check:

    Mixin params = CSS properties [OK]
Hint: Repeat columns with 1fr for equal width [OK]
Common Mistakes:
  • Confusing flex with grid display
  • Writing grid-template-columns: 3fr instead of repeat()
  • Using display:block by mistake
4. Identify the error in this Sass grid mixin:
@mixin grid($cols, $gap) {
  display: grid;
  grid-template-columns: repeat($cols 1fr);
  gap: $gap;
}
medium
A. gap property is invalid in grid layouts
B. Using display:flex instead of display:grid
C. Mixin parameters should be $columns and $gaps
D. Missing comma between $cols and 1fr in repeat() function

Solution

  1. Step 1: Check syntax of repeat() function

    The repeat() function requires a comma between the number and the size, like repeat($cols, 1fr).
  2. Step 2: Verify other properties

    Display is correctly set to grid, and gap is valid for grid layouts.
  3. Final Answer:

    Missing comma between $cols and 1fr in repeat() function -> Option D
  4. Quick Check:

    repeat() needs comma [OK]
Hint: Always put a comma inside repeat() between count and size [OK]
Common Mistakes:
  • Omitting comma in repeat()
  • Confusing display:flex with grid
  • Thinking gap is invalid in grid
5. You want a responsive grid mixin that changes columns based on screen width. Which Sass code correctly adds a media query inside the mixin to set 2 columns on screens smaller than 600px and 4 columns otherwise?
hard
A. @mixin responsive-grid($gap) { display: grid; grid-template-columns: repeat(2, 1fr); gap: $gap; @media (min-width: 600px) { grid-template-columns: repeat(4, 1fr); } }
B. @mixin responsive-grid($gap) { display: grid; grid-template-columns: repeat(4, 1fr); gap: $gap; @media (max-width: 600px) { grid-template-columns: repeat(2, 1fr); } }
C. @mixin responsive-grid($gap) { display: flex; gap: $gap; @media (max-width: 600px) { flex-direction: column; } }
D. @mixin responsive-grid($gap) { display: grid; grid-template-columns: repeat(4, 1fr); gap: $gap; @media (min-width: 600px) { grid-template-columns: repeat(2, 1fr); } }

Solution

  1. Step 1: Set default columns for large screens

    The mixin sets 4 columns by default using repeat(4, 1fr).
  2. Step 2: Add media query for smaller screens

    Inside @media (max-width: 600px), columns change to 2 with repeat(2, 1fr).
  3. Step 3: Confirm display and gap properties

    Display is grid and gap uses the parameter, which is correct.
  4. Final Answer:

    @mixin responsive-grid($gap) { display: grid; grid-template-columns: repeat(4, 1fr); gap: $gap; @media (max-width: 600px) { grid-template-columns: repeat(2, 1fr); } } -> Option B
  5. Quick Check:

    Default 4 cols, max-width 600px = 2 cols [OK]
Hint: Use max-width media query for smaller screens [OK]
Common Mistakes:
  • Using min-width instead of max-width for small screens
  • Setting flex display instead of grid
  • Reversing column counts in media query