Web Layout Using CSS Flexbox
In this tutorial, we will build a simple and responsive web layout using Flexbox.
1. HTML Structure
The HTML defines the structure of the layout:
<div class="flex-row">
<div class="flex-col">
<div class="box"></div>
</div>
<div class="flex-col">
<div class="box"></div>
</div>
<div class="flex-col">
<div class="box"></div>
</div>
</div>
Explanation:
- flex-row: A container that holds multiple columns and acts as a Flexbox container.
- flex-col: Individual columns within the row. Each column contains a box.
- box: Represents the content inside each column, styled with a background color and dimensions.
2. CSS Styling
The following CSS applies Flexbox properties to create the layout:
.box {
background-color: bisque;
min-height: 200px;
min-width: 250px;
}
.flex-row {
display: flex;
flex-wrap: wrap;
gap: 1.5rem;
}
.flex-col {
flex: 1;
}
Key Properties:
- .box: Adds a background color and defines the minimum dimensions for the boxes.
- .flex-row: Turns the container into a Flexbox layout with wrapping and gaps between items:
- display: flex: Enables Flexbox on the container.
- flex-wrap: wrap: Allows items to wrap to the next line if necessary.
- gap: Adds spacing between items.
- .flex-col: Distributes available space among the columns:
- flex: 1: Ensures all columns grow equally and take up available space.
3. How the Layout Works
Here’s how the Flexbox properties interact:
- Flex Container: The
.flex-row
uses Flexbox to align the columns horizontally and wraps them to the next line if needed. - Equal Widths: The
flex: 1
property ensures each column grows equally, making the layout responsive. - Spacing: The
gap
property ensures consistent spacing between the columns.
4. Responsive Design
The layout automatically adjusts to different screen sizes thanks to flex-wrap: wrap
. For more control, you can add media queries:
@media (max-width: 768px) {
.box {
min-width: 100%; /* Full width on smaller screens */
}
}
5. Complete Code
Here’s the full HTML and CSS code:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="flex.css" />
<title>Flex Web Layout</title>
</head>
<body>
<div class="flex-row">
<div class="flex-col">
<div class="box"></div>
</div>
<div class="flex-col">
<div class="box"></div>
</div>
<div class="flex-col">
<div class="box"></div>
</div>
</div>
</body>
</html>
Run Code
CSS
.box{
background-color: bisque;
min-height: 200px;
min-width: 250px;
}
.flex-row{
display: flex;
flex-wrap: wrap;
gap:1.5rem;
}
.flex-col{
flex:1;
}
Run Code
6. Summary
Using Flexbox, we created a responsive layout with evenly spaced columns and a clean design. Flexbox properties like flex-wrap
and gap
make the layout adaptable to various screen sizes without additional configurations.