Design responsive layout system using only 40 lines —Know how to implement col-sm-12 and col-md-6

If you’ve used Bootstrap, you’ve must applied some class name like these for responsive web design(RWD), would you want to know how it works? Let’s step by step to find the magic behind this!

Chinese version: 40行實作響應式的佈局系統 — 告訴你col-sm-12、col-md-6 是如何實現

Demo
  • Known SCSS & is point to the nested element
  • Known about CSS Flex
  • Known media query

This article is for someone like me, who wanna find out the responsive implementation in book shop, but most books only teach “how to use Bootstrap“, lol.

About Bootstrap Grid system

For the user who are not familiar with front-end, the bootstrap is really helpful to do the layout, by adding class name like .row / .col / .col-sm-3, we can easily put the container/element to the corresponding size and ratio.

src. Bootstrap Document
<div class="container">
<div class="row">
<div class="col">
1 of 2
</div>
<div class="col">
2 of 2
</div>
</div>
<div class="row">
<div class="col">
1 of 3
</div>
<div class="col">
2 of 3
</div>
<div class="col">
3 of 3
</div>
</div>
</div>
wide screen vs narrow screen
  • In corresponding place by ratio

Implementation

The following two items we want to implement are:

  1. Responsive, using different ratio by breakpoint

Layout — row and column

Let’s back to check the simple example, it should be like:

.row{
/**
* Do what?
* display : ??;
*
* wrap to next line?
* ??????? : wrap;
**/
}
.row {
display: flex;
flex-wrap: wrap;
}
.col{
flex-grow: 1;
margin: 15px;
}
If you see this on Medium, you might get the wrap result, just click 1x, 0.5x, 0.25x to see.

Responsive (1. ratio) — col-1~col-2

We have all 12 grids at all, let’s calculate in each case.

@for $i from 1 through 12 {
.col-#{$i} {
flex-grow:0;
flex-basis: calc(-30px + 100% *#{$i}* 1/12);
}
}
3 : 2 : 5 : 2

Responsive (2. breakpoint) — what’s the sm, md, lg?

We don’t need to find the answer in urgent, let’s think in same figure as above, think what it represent for.

<div class="col col-12 col-sm-6 col-md-4 col-lg-2" />
// <sm
12
12
12
12
12
12
// sm
6 6
6 6
6 6
// md
4 4 4
4 4 4
// lg
2 2 2 2 2 2

Let’s add these conditions

We all know about there’s a thing’s named media query could help us define style rule in different device width, but what’s the rule we need?

@media (min-width: 576px) {
@for $i from 1 through 12 {
&.col-sm-#{$i} {
//grow、basis...blabla
}
}
}@media (min-width: 768) {
@for $i from 1 through 12 {
&.col-md-#{$i} {
//grow、basis...blabla
}
}
}.
.
.

Conclusion

I could tell you this grid system I design would be the ugliest code, since it’s for tutorial purpose.

Yup, we step by step to finish the general responsive design system!

Let’s check the answer with Bootstrap source code

.col-sm-2 {
flex: 0 0 16.666667%;
max-width: 16.666667%;
}

If any interest, 👉 https://realdennis.me.