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.
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%;
}
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?
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>
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 */
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With