6

I want to create a grid of responsive 4x4 squares with a margin of exactly 20px on the left and right sides of the overall container. Furthermore, this would effectively eliminate the left margin on the first squares in each row and also eliminate the right margin on the last squares in each row since double margins aren't needed.

The green color notes the 20px margins on each side.

enter image description here

I've so far created the grid of squares with percentages but the problem is that, since I am applying a margin to all sides of each square, this method does not guarantee a left and right margin (on the container) of 20px each.

Fiddle: http://jsfiddle.net/p9qdhfub/1/

HTML

<section>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</section>

CSS

div {
    background: #000;
    float: left;
    height: 24vw;
    margin: 1%;
    width: 23%;
}

Question

How would I be able to create a 4x4 responsive grid of squares with the container (i.e. section) always having a margin-left of 20px and a margin-right of 20px?

web-tiki
  • 99,765
  • 32
  • 217
  • 249
J82
  • 8,267
  • 23
  • 58
  • 87

2 Answers2

6

You can simply add

section{
    margin:-1%;
    padding:20px;
}

DEMO

This way you can have your 20px fixed gutters on each side of the container. To remove the horizontal scrollbar, you can add an other container with overflow:hidden;

DEMO

html,
body {
  margin: 0;
}
.w {
  overflow: hidden;
}
section {
  margin: -1%;
  padding: 20px;
}
section div {
  background: #000;
  float: left;
  height: 24vw;
  margin: 1%;
  width: 23%;
}
<div class="w">
  <section>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
  </section>
</div>
web-tiki
  • 99,765
  • 32
  • 217
  • 249
2

jsfiddle demo

Section will always have 20px margin;
Every first(+4) DIV will have a left margin of 0;
Every fourth DIV will have a right margin of 0;

div {
    background: #000;
    float: left;
    height: 24vw;
    margin: 1%;
    width: 23.5%;
}
div:nth-child(4n-3){
    background:red;
    margin-left:0; /* or use 20px */
}
div:nth-child(4n){
    background:blue;
    margin-right:0; /* or use 20px */
}
section{
    margin:0 20px; /* so you don't need this any more */
}
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • This one nails it in my opinion - the only thing I'd add that instead of putting `height:24vw` you can get a nice 'square' appearance by doing an after element with `content:'';display:block;position:relative;padding-bottom:100%;` like so: http://jsfiddle.net/p9qdhfub/11/ – Djave Dec 30 '14 at 18:37