1

I am trying to create a 4x4 box. Why does the 4th div in a row jump to the next row, when it the width of the child div is 25%. Shouldn't it jump every 4 divs instead?

HTML

<div class="container"></div>

CSS

.container {
  display: flex;
  width: 600px;
  height: 600px;
  flex-wrap: wrap;
}
.item {
  border: 1px solid black;
  background-color: yellow;

}

JS

const container = document.querySelector(".container");
const calcWidth = 100/4;
for (let i = 0; i < 16; i++) {
  const item = document.createElement("div");
  item.classList.add("item");
  item.style.width = `${calcWidth}%`;
  item.style.height = `${calcWidth}%`;
  container.appendChild(item);
}

https://codepen.io/pepegaa/pen/VwjZdEW

J. Wilshere
  • 47
  • 1
  • 8

1 Answers1

1

The border adds an extra 2px to the width, use this so elements don't change size when adding borders/padding:

* {
    box-sizing: border-box;
}

const container = document.querySelector(".container");
const calcWidth = 100 / 4;
for (let i = 0; i < 16; i++) {
  const item = document.createElement("div");
  item.classList.add("item");
  item.style.width = `${calcWidth}%`;
  item.style.height = `${calcWidth}%`;
  container.appendChild(item);
}
* {
  box-sizing: border-box;
}

.container {
  display: flex;
  width: 600px;
  height: 600px;
  flex-wrap: wrap;
}

.item {
  border: 1px solid black;
  background-color: yellow;
}
<div class="container"></div>
dantheman
  • 3,189
  • 2
  • 10
  • 18