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

让人想犯罪 __ 提交于 2019-12-07 06:56:21

问题


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%;
}

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?


回答1:


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>



回答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 */
}


来源:https://stackoverflow.com/questions/27710062/create-a-4x4-responsive-grid-of-squares-with-a-margin-of-20px-on-each-side-of-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!