Skip to content

Instantly share code, notes, and snippets.

@chris13524
Created October 18, 2019 13:53
Show Gist options
  • Save chris13524/642292e31be2a4975b0101fa39be29fe to your computer and use it in GitHub Desktop.
Save chris13524/642292e31be2a4975b0101fa39be29fe to your computer and use it in GitHub Desktop.
Subgrid polyfill
subgridPolyfill(parent: HTMLElement, mode: "rows" | "columns") {
const go = () => {
const parentStyle = getComputedStyle(parent);
if (parentStyle.display != "grid") return;
const subgrids = Array.from(parent.children);
for (const child of subgrids) {
if (!(child instanceof HTMLElement)) throw new Error("child not instance of HtmlElement");
if (mode == "rows") {
child.style.gridTemplateRows = null;
child.style.gridAutoRows = "0px";
} else {
child.style.gridTemplateColumns = null;
child.style.gridAutoColumns = "0px";
}
}
const sizes = [];
for (const subgrid of subgrids) {
const subgridStyle = getComputedStyle(subgrid);
if (subgridStyle.display != "grid") continue;
for (let i = 0; i < subgrid.children.length; i++) {
if (sizes.length <= i) sizes.push(0);
const element = subgrid.children[i];
const elementStyle = getComputedStyle(element);
const styleToPixels = (style: string | null): number => {
if (style == null) style = "0px";
return +style.substring(0, style.length - 2);
};
const elementSize = mode == "rows" ?
element.scrollHeight + styleToPixels(elementStyle.marginTop) + styleToPixels(elementStyle.marginBottom) :
element.scrollWidth + styleToPixels(elementStyle.marginLeft) + styleToPixels(elementStyle.marginRight);
if (elementSize > sizes[i]) sizes[i] = elementSize;
}
}
let sizesString = "";
for (const size of sizes) {
sizesString += size + "px ";
}
for (const child of subgrids) {
if (!(child instanceof HTMLElement)) throw new Error("child not instance of HtmlElement");
if (mode == "rows") {
child.style.gridTemplateRows = sizesString;
child.style.gridAutoRows = null;
} else {
child.style.gridTemplateColumns = sizesString;
child.style.gridAutoColumns = null;
}
}
};
window.addEventListener("resize", go);
this.sub(new Subscription(() => window.removeEventListener("resize", go)));
go();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment