为simplegrid.io添加col-offset-X列偏移功能的技术问询
Hey there! Let's sort out the column offset implementation for your SimpleGrid setup. First, let's break down what's off with your current code and then build the correct solution that aligns perfectly with the existing grid system.
What's Wrong with Your Current Offset Class?
Your current code:
.col-offset-1 { margin-left: ($width / 12) + ($gutter / 2)!important; }
Has two key issues:
- Incorrect calculation: The formula doesn't account for how SimpleGrid calculates column widths. The grid uses a gutter system where each column has
2%left/right margin, and the column width itself is adjusted to fit 12 columns within the row. Your current math creates an offset larger than a single column's actual occupied space. - Unnecessary
!important: The.col-offset-Xclass has higher specificity than the base.row [class^="col"]margin rule, so you don't need to force it with!important.
Correct Offset Calculation
SimpleGrid's total row width is 100%, split into 12 equal "slots" (each slot = 100%/12 ≈ 8.333%). Each column occupies one slot: its width + 2% left + 2% right margin equals one slot.
To offset a column by X slots, we need to:
- Calculate the total width of
Xslots - Subtract the column's default
2%left margin (since it's already included in the slot width)
In Sass, this translates to:
$col-slot-width: ($width + $gutter) / 12; // = 100%/12, since $width + $gutter = 100% .col-offset-X { margin-left: ($col-slot-width * $X) - ($gutter / 2); }
Full Implementation (Mobile + Desktop)
To match SimpleGrid's responsive structure, we'll generate offset classes for both mobile (-sm suffix) and desktop (medium breakpoint and up) using Sass loops to avoid repetitive code:
// Mobile offsets (applies by default, like .col-X-sm) @for $i from 1 through 12 { .col-offset-#{$i}-sm { margin-left: (($width + $gutter) / 12 * $i) - ($gutter / 2); } } // Desktop offsets (applies at medium breakpoint, like .col-X) @media only screen and (min-width: $breakpoint-med) { @for $i from 1 through 12 { .col-offset-#{$i} { margin-left: (($width + $gutter) / 12 * $i) - ($gutter / 2); } } }
How to Use It
This integrates seamlessly with existing SimpleGrid classes. For example:
- Offset a column by 3 slots on mobile:
<div class="col-6-sm col-offset-3-sm">...</div> - Offset a column by 2 slots on desktop:
<div class="col-8 col-offset-2">...</div>
Verification
Let's test with col-offset-1 (desktop):
- Slot width =
100%/12 ≈8.333% - Offset calculation:
8.333% - 2% =6.333% - Total left space from row edge:
6.333% (offset) +2% (column's default margin) =8.333%— exactly one full column slot, which is what we want!
This implementation stays true to SimpleGrid's original gutter and width logic, ensuring full compatibility with the rest of the system.
内容的提问来源于stack exchange,提问作者Lovelock

