Skip to content

Instantly share code, notes, and snippets.

@ianmcnally
Last active February 24, 2019 11:21
Show Gist options
  • Save ianmcnally/3bc8fa64dc1fb35e47deeb7e449265ce to your computer and use it in GitHub Desktop.
Save ianmcnally/3bc8fa64dc1fb35e47deeb7e449265ce to your computer and use it in GitHub Desktop.
Grid auto placement polyfill
import { columns, display, gridSpans, margin } from './css-modules-styles'
const COLUMNS = 12
const toArray = arrayLike => Array.prototype.slice.call(arrayLike)
const placeItemsOnGrid = grid => {
const withGutters = grid.classList.contains(columns.withGutters)
let currentColumnSpansInRow = 0
let currentRow = 1
let currentColumn = 1
toArray(grid.children).forEach(row => {
let columnSpan
for (let i = 0; i <= COLUMNS; i++) {
if (row.classList.contains(gridSpans[`column${i}`])) {
columnSpan = i
break
}
}
const wouldNextSpansExceedColumnCount =
currentColumnSpansInRow + Number(columnSpan) > COLUMNS
if (wouldNextSpansExceedColumnCount) {
currentRow += 1
currentColumnSpansInRow = 0
currentColumn = 1
}
currentColumnSpansInRow = currentColumnSpansInRow + Number(columnSpan)
row.style['-ms-grid-column-span'] = columnSpan
row.style['-ms-grid-column'] = currentColumn
row.style['-ms-grid-row'] = currentRow
if (withGutters) {
row.classList.add(margin.leftOne)
}
currentColumn += columnSpan
})
}
const runPolyfill = () => {
const grids = document.getElementsByClassName(display.grid)
toArray(grids).forEach(placeItemsOnGrid)
}
const supportsGrid = typeof CSS !== 'undefined' &&
typeof CSS.supports !== 'undefined' &&
CSS.supports('display', 'grid')
if (!supportsGrid) {
// covers dynamic and static pages, at the cost of multiple DOM traversals
window.addEventListener('popstate', runPolyfill)
document.addEventListener('DOMContentLoaded', runPolyfill)
document.body.addEventListener('DOMSubtreeModified', runPolyfill)
}
.of12 {
-ms-grid-columns: (1fr)[12];
grid-template-columns: repeat(12, 1fr);
}
.auto {
-ms-grid-rows: auto;
grid-template-rows: auto;
}
.grid {
display: -ms-grid;
display: grid;
}
@camilaFarelo
Copy link

Hi :) I have a question. from where do you get css-modules-styles?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment