Custom grid layout

In here I will try to make a custom grid layout just like bootstrap does. The basic thing before you do that is to keep in mind how many grids do you want to break your page into. You can have 4 or 10 or say twelve as bootstrap does. They do have their reasons for keeping a 12 column grid but the truth is many a times you’d be needing a custom grid layout with maybe 5 items in row rather than multiple of 12. So how do u do that. First of all you have to define a class say

.row {
margin: 0 auto 1em auto;
}
.row:after {
display: table;
content: '';
clear:both;
}

As you can see I have made class with a name of “row”. And i have used a pseudo selector “after” on “row” just to ensure that the parent container takes the height of its child. Normally u might have seen that when you make elements to float. either left or right, they float out of parent’s scope. They kind of take a new z-dimension. So the overall height of the parent reduces to 0. To avoid that, I mean i can’t avoid float to change its behaviour. But with using display table on after the parent takes the height of its child as if they were inline elements.

Now as we have covered this portion quite well, we’ll move onto the grid section. Now i am naming the classes just like bootstrap does. I am using “col” class to signify the column and “s3” to signify the width it would take. So you can do your maths and figure out how much width do u need for your column based on this.

.row .col.s3 {
width: 25%;
}

.row .col {
float: left;
padding: 0 0.5em;
box-sizing: border-box;
}

Now the thing is that you can specify any amount of width in percentage depending on your requirement but to keep them in the same line with the padding mentioned for them is tricky. If you have given float left to all the columns it’s fine but as soon as you throw a padding left or right the grid breaks as the box element will start to expand according to the padding u would have given to it. To keep the div to stay as a fix width div what you need to do is change the box-sizing property of the div. Now when i do box-sizing :border-box. The target element is restricted to its fix width regardless of the padding that you give. The padding will be taken inwards.

So that is it. You can place a few hacks to accomplish this. But the box-sizing property was the thing that surprised me. I’ll be back with more.

Author: shellophobia

just passing time here.. and enjoying

Leave a comment