I am trying to apply different gap between each grid element, for example we are having the following code. 4 Grid lines, 3 Elements and a 10px width between each grid-box. How can i apply custom width between each grid-box? for example 20px between element1 and element2, and then 30px between element2 and element3?
Can i achieve that with the css grids?
Edit: Without using padding. Edit2: Provided Pictre.
Click for picture preview
html, body {height: 100%; margin: 0; padding: 0;}
body {
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
grid-template-row: 1fr 1fr;
grid-column-gap: 10px;
grid-row-gap: 10px;
}
#element1 {
grid-column: 1/2;
grid-row: 1/2;
border: 1px solid #2e2e2e;
color: #000;
}
#element2 {
grid-column: 2/3;
grid-row: 1/2;
border: 1px solid #2e2e2e;
color: #000;
}
#element3 {
grid-column: 3/4;
grid-row: 1/2;
border: 1px solid #2e2e2e;
color: #000;
}
<div id="element1">element1</div>
<div id="element2">element2</div>
<div id="element3">element3</div>
The vertical gaps are caused by the images not filling the vertical space in the grid items. The problem is made worse with align-items: center on the container, which removes the align-items: stretch default. Essentially, there are no gaps between grid items.
grid-gap is the idiomatic approach for spacing grid items, but it's not ideal since grid gaps are just that: empty space, not physical boxes. To that end, the only way to color these gaps is to apply a background color to the grid container.
Well the general approach that I like to use with css-grid is to make extra columns. Obviously use grid-column-gap
and grid-row-gap
if you have the same padding, but if not you can add token columns.
You can totally use padding/ margin for this, but I like the extra column a bit better, since in css-grid you define the layout in the wrapper and this is where this belongs to semantically. You also do not have to apply it to every single item in those columns. (Also, do you apply it to the left or the right or both items?).
Yes, that is why you never use numbers to describe an area in css grid!
You can name your lines and with it your areas. Use this! You can use the grid-template-areas
for this ore simply name it like this:
grid-template-columns: [left-start] auto [left-end right-start] auto [right-end];
Oh you want extra padding? Here you go:
grid-template-columns: [left-start] auto [left-end] 10px [right-start] auto [right-end];
Note that I am by no means a seasoned web developer (quite the opposite), but I think this approach might - generally - be the best one.
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