Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a 4x4 responsive grid of squares with a margin of 20px on each side of the container? [duplicate]

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?

like image 254
J82 Avatar asked Dec 30 '14 17:12

J82


2 Answers

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>
like image 145
web-tiki Avatar answered Nov 08 '22 23:11

web-tiki


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 */
}
like image 2
Roko C. Buljan Avatar answered Nov 08 '22 23:11

Roko C. Buljan