I am looking to create a grid layout where each child element represents an individual grid square.
However, I am facing an issue with spacing between the children and the parent container, which is not desired. How can I eliminate this unwanted space?
Using negative margin on the parent div shifts the entire grid, resulting in it being off-center on the page.
The main objective here is to make the grid fully responsive, hence my use of floating elements and relative widths.
This is how I envision the layout to appear (with 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;
/* Ensures padding expands inwards */
padding: 5px;
/* Using width instead of margin for relative width compatibility, resulting in 10px spacing between children */
width: 25%;
height: 100px;
float: left;
}
.child>div {
/* Represents content within each child element */
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>