Search code examples
csscss-grid

CSS Grids. Different gap between each grid


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 Picture.

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>


Solution

  • 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.

    Why not padding/ margin?

    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?).

    But this messes up my numbering

    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.