SimpleTuts.com

Responsive Flexbox Web Layout with Different Width Columns

In this tutorial, we will create a responsive layout with two columns of different widths using Flexbox.

1. HTML Structure

Below is the HTML structure of the layout:

<div class="container">
  <div class="column left">30% Column</div>
  <div class="column right">70% Column</div>
</div>

Explanation:

2. CSS Styling

Below is the CSS code that applies Flexbox properties to create the layout:

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  font-family: Arial, sans-serif;
}

.container {
  display: flex;
  flex-wrap: wrap; /* Allows the columns to wrap on smaller screens */
}

.column {
  padding: 20px; /* Adds spacing inside the columns */
}

.left {
  flex: 0 0 30%; /* Takes 30% of the container width */
  background-color: #747070; /* Light gray for visibility */
}

.right {
  flex: 0 0 70%; /* Takes 70% of the container width */
  background-color: #51517c; /* Light blue for visibility */
}

/* Responsive Design */
@media (max-width: 768px) {
  .left, .right {
    flex: 0 0 100%; /* Stacks the columns on smaller screens */
  }
}
  

Key CSS Properties:

3. Responsive Design

With the media query, the layout adapts for smaller screens. Here's the effect:

4. Complete Code

Here’s the full HTML and CSS code for the layout:

HTML


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Responsive Flex Layout</title>
    <link rel="stylesheet" href="flex-difcols.css" />
  </head>
  <body>
    <div class="container">
      <div class="column left">30% Column</div>
      <div class="column right">70% Column</div>
    </div>
  </body>
</html>
Run Code

CSS


*{
    box-sizing: border-box;
}

body{
    margin: 0;
    font-family: Arial, sans-serif;
}

.container{
    display: flex;
    flex-wrap: wrap; /* Allows for responsiveness */
}

.column {
    padding: 20px; /* Add some padding */
}

.left {
    flex: 0 0 30%; /* 30% width */
    background-color: #747070; /* Light gray for visibility */
}

.right {
    flex: 0 0 70%; /* 70% width */
    background-color: #51517c; /* Light blue for visibility */
}

/* Media query for smaller screens */

@media (max-width: 768px){
    .left, .right{
        flex: 0 0 100%; /* stack columns on smaller screens */
    }
}
Run Code

5. Summary

Using Flexbox, we created a responsive layout with two columns of different widths. The Flexbox properties allow for a clean, responsive design without complex float or positioning rules. The layout adjusts seamlessly across devices.