Loading course content...
Loading course content...
Code Playground is only enabled on larger screen sizes.
Now, we come to the most important topic in responsive design: how to create a webpage layout that adapts to the viewport size.
For demonstration purposes, we are going to build a responsive page layout with a navigation bar, two sidebars (left and right), a main content section, as well as a footer, as shown in the diagram below.

The HTML code is rather simple:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Flexbox Responsive Layout</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="nav">Navbar</div>
<div class="side-primary">Primary sidebar</div>
<div class="content">
Main Content
<p>. . .</p>
</div>
<div class="side-secondary">Secondary sidebar</div>
<div class="footer">Footer</div>
</div>
</body>
</html>First of all, the container should have a flexbox layout by setting display to flex.
The flexbox layout is responsive by default when you set flex-direction to row and flex-wrap to wrap. The next element will automatically occupy the next row when there is not enough space.
/* . . . */
.container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}Remember, since we are following the mobile-first rule, so for small screens, each section should take up all the horizontal space available.
/* . . . */
.container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.container > div {
width: 100%;
}For medium size screens, the setup is a bit more complicated but also more flexible.
For instance, you can keep the navbar and footer to occupy 100% of the horizontal space. And then, let the sidebar and the main content section take the same row.
@media screen and (min-width: 640px) {
.nav {
width: 100%;
}
.side-primary {
flex: 1;
}
.content {
flex: 3;
}
.side-secondary {
display: none;
}
.footer {
width: 100%;
}
}For larger screens, the secondary sidebar should be displayed. It will take up the same amount of space as the primary sidebar.
@media screen and (min-width: 1024px) {
.nav {
width: 100%;
}
.side-primary {
flex: 1;
}
.content {
flex: 3;
}
.side-secondary {
display: block;
flex: 1;
}
.footer {
width: 100%;
}
}<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="/styles.css"> </head> <body> <div class="container"> <div class="nav">Navbar</div> <div class="side-primary">Primary sidebar</div> <div class="content"> Main Content <p>. . .</p> </div> <div class="side-secondary">Secondary sidebar</div> <div class="footer">Footer</div> </div> </body> </html>