Как масштабировать квадратную CSS сетку с учетом ширины и высоты родителя - PullRequest
0 голосов
/ 16 января 2020

Я пытаюсь вписать рекурсивно сгенерированную сетку в container, но при каждой depth рекурсии общий размер сетки увеличивается и в конечном итоге просачивается. Я могу ограничить ширину сетки, установив #container { width: 800px; height: 800px; }, но он не учитывает атрибут контейнера height.

Я впервые играю с DOM, поэтому извиняюсь, если что-то не так. c.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Tic Tac Toe</title>
    <link href="style.css" rel="stylesheet">
</head>
<body>
    <div id="container"></div>
    <script src="index.js"></script>
</body>
</html>
* {
    box-sizing: border-box;
}

.grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(3, 1fr);
    grid-gap: 0.5%;
    background-color: black;
}

.tile {
    background-color: white;
    display: flex;
    justify-content: center;
    align-items: center;
}
"use strict;"

// Returns the tile ('x', 'o') given an index
// 0 - 'x'
// 1 - 'o'
function tile(id) {
    if (id !== 0 && id !== 1) {
        throw `Parameter ${id} not found`;
    }
    let text = id === 0 ? 'X' : 'O';
    let element = document.createElement("div");
    element.classList.add("tile", text);
    element.innerText = text;
    return element;
}

function grid() {
    let node = document.createElement("div");
    node.classList.add("grid");
    return node
}

function recurse(parent, tileID, seen, depth) {
    if (depth < 0) { return; }
    let prevState = parent.cloneNode(true);
    for (let i = 0; i < 9; i++) {
        if (seen.has(i)) { continue; }
        seen.add(i);
        let item = positionedItem(gridWithTile(prevState, tileID, i), i);
        parent.appendChild(item);
        recurse(item, 1 - tileID, seen, depth-1);
        seen.delete(i); 
    }
    return parent;
}

function gridWithTile(grid, tileID, i) {
    let node = grid.cloneNode(true);
    node.appendChild(positionedItem(tile(tileID), i));
    return node;
}

function generate(container) {
    recurse(container, 0, new Set(),2);
}

function positionedItem(node, idx) {
    let { row, col } = rowcol(idx);
    node.style.gridRowStart = `${row + 1}`;
    node.style.gridRowEnd = `${row + 2}`;
    node.style.gridColumnStart = `${col + 1}`;
    node.style.gridColumnEnd = `${col + 2}`;
    return node;
}

function uid(row, col) {
    return row * 3 + col;
}

function rowcol(uid) {
    return {
        'row': Math.floor(uid / 3),
        'col': uid % 3
    };
}

let firstGrid = grid();
document.getElementById("container").appendChild(firstGrid);
generate(firstGrid);

Codepen

...