CSS Grid: Why do my boxes extend beyond their container?

I’ve applied box-sizing: border-box to seemingly every element. I set the container width to 300px and the grid-template-columns to 3 100px . Why then do my individual divs with the class items extend beyond the container?

<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 class="item">7</div>
  <div class="item">8</div>
  <div class="item">9</div>
  <div class="item">10</div>

* {
  box-sizing: border-box;

.item {
  border: 1px solid #000;
  box-sizing: border-box;

.container {
  display: grid;
  grid-template-columns: 100px 100px 100px;
  border: 3px solid red;
  width: 300px;

Because when you put the 3px border on the container it pushes the elements inside the container to the right, but still not changing the width of the container. So essentially, the items inside it moved but the container didn’t change it’s size to resize with the items inside it. If you change the border size to 1px, it will perfectly line up with the boxes. If you want the container to resize with its content, just remove the box-sizing attribute.

1 Like

@Catalactics Ok thanks. It confuses me because I thought the whole point of box-sizing: border-box; was that if you added borders/padding, it would absorb them within the defined size? Apparently “absorbing” them inside the container means the elements inside the container don’t start until after the border? It’s almost like I want the elements within to have a position: absolute within the container- meaning starting on top of the border rather than after it. I want the container and the elements to start at the exact same spot, regardless of the borders.

1 Like

With the default box-sizing: content-box on the grid it would work like you are expecting it to.

With box-sizing: border-box, the element width is:

width = (border) + (padding) + (width of the content)

Which means the content is:

content = (width of the content) - (border + padding)

MDN: box-sizing: values

Note that padding and border will be inside of the box. For example, .box {width: 350px; border: 10px solid black;} renders a box that is 350px wide, with the area for content being 330px wide.


1 Like