Search code examples
htmlcssgrid-layoutcss-grid

A grid with spacing / gutters between items, but not between items and the container


So I want to create a grid where the children are the individual grid squares.

However, I have spacing between the children and the parent, which I don't want. How do I remove that?

Negative margin on the parent moves the whole thing, which decenters it on the page.

The goal is to have the whole thing be responsive, which is why I use floating and relative widths.

The way I would like it to look is like this (10px spacing):

+-----+--+-----+--+-----+--+-----+
|xxxxx|  |xxxxx|  |xxxxx|  |xxxxx|
|xxxxx|  |xxxxx|  |xxxxx|  |xxxxx|
|xxxxx|  |xxxxx|  |xxxxx|  |xxxxx|
+-----+  +-----+  +-----+  +-----+
|                                |
+-----+  +-----+                 |
|xxxxx|  |xxxxx|                 |
|xxxxx|  |xxxxx|                 |
|xxxxx|  |xxxxx|                 |
+--------------------------------+

#parent {
  width: 500px;
  height: 500px;
  background-color: #CCCCCC;
}

.child {
  box-sizing: border-box;
  /* So the padding expands inwards */
  padding: 5px;
  /* Replacement to margin so relative width works, spacing between children ends out to be 10px of course */
  width: 25%;
  height: 100px;
  float: left;
}

.child>div {
  /* This represents content of the child */
  width: 100%;
  height: 100%;
  background-color: #000000;
}
<div id=parent>
  <div class=child>
    <div></div>
  </div>
  <div class=child>
    <div></div>
  </div>
  <div class=child>
    <div></div>
  </div>
  <div class=child>
    <div></div>
  </div>
  <div class=child>
    <div></div>
  </div>
  <div class=child>
    <div></div>
  </div>
</div>


Solution

  • How about something like this:

    .child { padding: 0 5px 5px 0;}
    .child:nth-child(4n){ padding-right: 0;}
    

    See working demo below:

    #parent {
      width: 500px;
      height: 500px;
      background-color: #CCCCCC;
    }
    
    .child {
      box-sizing: border-box;
      width: 25%;
      height: 100px;
      float: left;
      padding: 0 5px 5px 0;
    }
    
    .child:nth-child(4n) {
      padding-right: 0;
    }
    
    .child>div {
      /* This represents content of the child */
      width: 100%;
      height: 100%;
      background-color: #000000;
    }
    <div id=parent>
        <div class=child><div></div></div>
        <div class=child><div></div></div>
        <div class=child><div></div></div>
        <div class=child><div></div></div>
        <div class=child><div></div></div>
        <div class=child><div></div></div>
        <div class=child><div></div></div>
        <div class=child><div></div></div>
        <div class=child><div></div></div>
        <div class=child><div></div></div>
    </div>