I'm trying to create a column grid where each grid-item has some dynamic width or it can have 0 width also, but because of using grid-gap, even if the width is 0, it's creating a gap.
So, if you see in the third row, we have empty space before the green column, same in the second row after the blue column, how to avoid this?
Just based on the way you have your markup and styling a quick fix would be to add a .child
declaration and set margin: 0 3px;
(or whatever size makes sense) and then set grid-gap: 0;
in .item
. See snippet below.
body {
font-family: sans-serif;
}
.item {
display: grid;
height: 20px;
grid-gap: 0;
margin-bottom: 5px;
width: 200px;
}
.item1 {
grid-template-columns: 50% 0px 50% 0;
}
.item2 {
grid-template-columns: 0px 50% 0 50%;
}
.item3 {
grid-template-columns: 25% 25% 25% 25%;
}
.child {
margin: 0 3px;
}
.child1 {
background-color: red;
}
.child2 {
background-color: green;
}
.child3 {
background-color: blue;
}
.child4 {
background-color: black;
}
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app">
<div class="grid">
<div class="item item3">
<div class="child child1"></div>
<div class="child child2"></div>
<div class="child child3"></div>
<div class="child child4"></div>
</div>
<div class="item item1">
<div class="child child1"></div>
<div class="child child2"></div>
<div class="child child3"></div>
<div class="child child4"></div>
</div>
<div class="item item2">
<div class="child child1"></div>
<div class="child child2"></div>
<div class="child child3"></div>
<div class="child child4"></div>
</div>
<div class="item item3">
<div class="child child1"></div>
<div class="child child2"></div>
<div class="child child3"></div>
<div class="child child4"></div>
</div>
</div>
</div>
</body>
</html>