In this article, I’ll be showing you how to easily create responsive multi-column mobile friendly layouts using CSS Flexbox.
What are we building?
Four Column Responsive Flexbox Layout
The four column HTML markup has a top-level section element with the class name row and of course four div’s with class column inside representing the four columns.
<div class="row"> <div class="column" style="background:#aaa;">1</div> <div class="column" style="background:#bbb;">2</div> <div class="column" style="background:#ccc;">3</div> <div class="column" style="background:#ddd;">4</div> </div>
As you know, div is a block-level element so the output with the above code looks like the image below.
To make the four column layout, we need to make both divs appear beside each other instead of below the other
With Flexbox, we can do it with a couple of CSS Flexbox properties:
- display:flex
- flex-wrap: It defines whether the flex items are forced in a single line or can be flowed into multiple lines.
.row { display:flex; flex-wrap: wrap; }
We can then set the column width i.e, 100% / 4 = 25% each:
.column { width: 25%; }
To make it responsive for tablets and mobile we can use CSS Media Queries. We can set the width of each column in tabs 25% and for mobile 50%. For mobile we need to add the flex-direction property and set the value value to column so the elements can be adjustes side by side in one row.
/*For tablet*/ @media(max-width: 1024px) { .column { width: 25%; } } /*For Mobiles*/ @media(max-width: 767px) { .column { width: 100%; flex-direction: column; } }
Here is what we have achieved:
For Desktop:
For Mobile: