CSS Grid兼容微软浏览器及Sass混合写法正确性咨询
Hey there! Let's break down your questions clearly:
Yes, your mixin is perfectly valid for your use case!
The grid shorthand property lets you define grid-template-rows / grid-template-columns directly when you don't need to set other grid-related values like grid-template-areas or grid-auto-flow. Your mixin:
@mixin grid-template($row,$col){ grid: repeat($row, 1fr) / repeat($col,1fr); }
When called with @include grid-template(1,2);, it compiles to:
grid: repeat(1, 1fr) / repeat(2, 1fr);
This is exactly equivalent to your original manual grid declaration, creating 1 row of 1fr height and 2 columns each of 1fr width. So this part works as intended.
-ms-grid prefix like that? Unfortunately, no—this approach won't work for IE 10/11. Here's why:
IE's grid implementation is based on an old, pre-standard version of the Grid spec that has almost no overlap with modern grid syntax. Key issues with your current prefix attempt:
- IE does not support the
repeat()function at all. You have to explicitly list every track size. - There is no
-ms-gridshorthand property. IE requires separate-ms-grid-rowsand-ms-grid-columnsproperties. - Even if you set the rows/columns correctly, IE will stack all grid items in the first cell unless you explicitly position them with
-ms-grid-rowand-ms-grid-column.
A corrected IE-compatible mixin
To add proper IE support, modify your mixin to generate explicit track lists for IE:
@mixin grid-template($row, $col) { // Modern standard grid grid: repeat($row, 1fr) / repeat($col, 1fr); // IE 10/11 compatibility $ie-row-tracks: (); @for $i from 1 through $row { $ie-row-tracks: append($ie-row-tracks, 1fr, space); } $ie-col-tracks: (); @for $i from 1 through $col { $ie-col-tracks: append($ie-col-tracks, 1fr, space); } -ms-grid-rows: #{$ie-row-tracks}; -ms-grid-columns: #{$ie-col-tracks}; }
This mixin uses Sass loops to build the explicit track lists IE requires, since repeat() isn't supported.
One more critical note for IE
Don't forget to position your grid items in IE! For example, a second column item needs:
.your-grid-item:nth-child(2) { -ms-grid-column: 2; }
Without this, all items will overlap in the first grid cell.
内容的提问来源于stack exchange,提问作者Giacomo Ciampoli

