create CSS grid without writing a div for each cell

Viewed 278

I need a grid with 100 cells for a battleship game I'm making (using html, css, and JavaScript), but I don't want to create 100 divs in html to make it.

<div class="container">
  <div class="item-1"></div>
  <div class="item-2"></div>
  <div class="item-3"></div>
  <div class="item-4"></div>
  <div class="item-5"></div>
  <div class="item-6"></div>
  ...
</div>

Is there way were I can avoid this and then just access them by parent in css?

.cell:nth-child(n) {
  //code
}

I know a way where I can work around this without using a grid, but this seems the most simple way if I can just get past this. Any help would be appreciated.

2 Answers

You can programmatically create them using Javascript:

var container = document.querySelector('.container')

for (var i = 0; i < 100; i++) {
  var el = document.createElement('div')
  el.classList.add('item-' + (i + 1))
  container.appendChild(el)
}

console.log(container.children.length) // 100
<div class="container"></div>

If you inspect by pressing Cmd/Ctrl+Shift+C in Chrome, you can see that there are a hundred divs.

Each of them has a class attribute that equals item-n, where n is a number between 1 and 100.

I thought you might need some CSS as well? I used @GalaxyCat105's script (above) and added some grid-style magic.

var container = document.querySelector('.container')

for (var i = 0; i < 100; i++) {
var el = document.createElement('div')
el.classList.add('item-' + (i + 1))
container.appendChild(el)
}

console.log(container.children.length) // 100
@import url('https://fonts.googleapis.com/css?family=Nunito+Sans:400,700|Cormorant+Garamond:300,700|Titillium+Web:200,200i,400,400i,700|Orbitron:700&display=swap');

:root {
    --color-woodsmoke:      #161B1E;
    --color-boulder:        #767676;
    --color-gallery:        #F0F0F0;
}

*, *:before, *:after {
    box-sizing: border-box;
}

body {
    font-family: 'Nunito Sans', sans-serif;
    font-size: 20px;
    line-height: 1.4;
    color: var(--color-woodsmoke);
    margin: 0;
}

h1 {
    font-size: 3rem;
    text-align: center;
}

.container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: .5em;
    padding: 1em;
}

[class^="item"] {
    min-height: 10em;
    background: var(--color-gallery);
    border: 1px solid var(--color-boulder);
    box-shadow: 1px 2px 4px rgba(0,0,0,0.04);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>100 Items</title>
</head>
<body>
    <h1>One hundred items</h1>
    <div class="container"></div>
</body>
</html>

Related