A responsive two-column layout is a layout in which our contents are divided into two sections. They are side by side on wider screens and on top of each other on narrow screens. Its width can be equal or not. In this article, we will create an unequal-width layout.
This webpage you're viewing is an example of a two-column layout.
This tutorial will only use two files named index.html and style.css.
-
Get Started with HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Responsive Two Column Layout using Flexbox</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="top-container"> <main class="main-content"> Here goes the main content... </main> <aside class="side-container"> <section class="side-content"> Here goes the side content... </section> <section class="side-content"> Here goes the side content... </section> </aside> </div> </body> </html>
In our html file, we have <main> and <aside> tags. The <main> tag will obviously be our bigger column and contain our main content. On the other hand, the <aside> will contain containers of our secondary contents as seen in the image above.
-
Add CSS
* { padding: 0; margin: 0; box-sizing: border-box; } body { font-family: sans-serif; background: hsl(0, 0%, 92%); } .top-container { display: flex; flex-wrap: wrap; padding: 20px; } .main-content { flex-basis: 75%; height: 80vh; } .side-content { height: 40vh; } .side-container { flex-basis: 25%; padding-left: 20px; } .main-content, .side-content { box-shadow: 0px 0px 8px hsl(0, 0%, 70%); padding: 10px; background: white; margin-bottom: 10px; } @media screen and (max-width: 992px) { .main-content, .side-container { flex-basis: 100%; } .top-container, .side-container { padding: 20px 0; } }
By using Flexbox in CSS, we can create a responsive layout with less code.
In our .main-content and .side-container, we manipulate the value of flex-basis by setting it to 75% on bigger columns and 25% on smaller columns to make it side by side on wider screens and changing it to 100% in media queries to make it on top of each other on narrow screens. To make that work, we use flex-wrap:wrap on .top-container.
The height:80vh on .main-content and height:40vh on .side-content are just there to make it look good while we don't have content yet. You may want to remove it when you already have your contents.
Challenge
Now that you know how to make a responsive two-column layout using Flexbox, I challenge you to continue it by putting contents in it. You can add a responsive navigation bar and a blog post with a title and image, and don't forget the side contents.