Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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

This comment has been minimized.

Show comment Hide comment
@camilaFarelo

camilaFarelo Dec 21, 2017

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

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