Search code examples
page-layoutcss

How do you put in percentage based margin to a CSS grid?


I'm trying to learn how to build a grid system - and so far this is what I've got. What I want to know is, how would I create actual gaps between the colums? If I put in a margin, everything goes out of the grid, because "box-sizing" only accounts for borders and padding. The only way I can think of doing it is to give every column a thick border.

Is there a way to get margins to work, so there's an actual space between the columns?


Solution

  • With a smart but basic use of pseudo classes, you can easily get a great solution.

    Let's assume your columns are using the class .column and you want 5 columns. That would be 20% each, minus a 2% gap (for example).

    First of all, with box-sizing: border-box; you include padding and borders in the width as you mentioned, which is a fairly good practice.

    .col {
    box-sizing: border-box;
    width: 18%;
    margin-right: 2%;
    }
    

    After that, for the last .col we can use the pseudo class :last-child and override the right margin, like this:

    .col:last-child {
    margin-right: 0;
    }
    

    The numbers on this example don't actually crunch right, but it illustrates a good way of achieving what you want while using a scalable and maintainable CSS code.

    EDIT: After reviewing your pen, I strongly advise against using the border to "separate" the columns. It's a visual hack and no more, one which actually depends on the background colour of your website. I recommend a detailed overview of how the "big shots" are doing it, such as Bootstrap or Foundation.