Flex Layout 1
Flexbox is like Lego blocks.
Just as you can stack Lego blocks to create the shapes you want, Flexbox allows you to stack elements on a web page to create the design you desire.
Previously, aligning content vertically and horizontally or centering it required complex CSS rules, but with Flexbox, you can effortlessly align elements.
.container { display: flex; justify-content: center; align-items: center; height: 100vh; }
Flex Container & Flex Items
In Flexbox, the box that wraps elements is called the Flex Container
, and the elements inside the box are called Flex Items.
-
Flex Container
: The parent element where the Flexbox layout is applied. The child elements within it are referred to as Flex Items. -
Flex Item
: Each element inside the Flex Container, which is arranged or aligned according to the Container's properties.
How to Use Flexbox
.container { display: flex; }
By adding the display: flex;
property as shown above, the element becomes a Flex Container. All its child elements automatically become Flex Items.
Main Properties of Flexbox
1. display: flex;
This property defines a Flex Container. When you apply the flex property, the child elements within the container become Flex Items.
.container { display: flex; }
2. flex-direction
This defines the direction in which Flex Items are placed. Setting it to row
arranges them horizontally, while setting it to column
arranges them vertically.
.container { flex-direction: row; /* or column */ }
3. flex-wrap
This determines whether Flex Items within the Flex Container should be placed on a single line or wrapped onto multiple lines as needed.
With flex-wrap: nowrap;
, Flex Items are forced onto a single line, while flex-wrap: wrap;
allows items to wrap onto new lines when they exceed the container's width.
.container { flex-wrap: nowrap; /* Place flex items on a single line */ }
Practice
Here's a simple implementation of a Flexbox layout:
<div class="flex-container"> <div class="box">1</div> <div class="box">2</div> <div class="box">3</div> <div class="box">4</div> </div>
.flex-container { display: flex; gap: 20px; padding: 20px; background-color: #ffffff; border-radius: 10px; box-shadow: 0px 4px 20px rgba(0, 0, 0, 0.1); } .box { padding: 30px; font-weight: bold; font-size: 20px; text-align: center; background-color: #c8e6c9; border-radius: 5px; }
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help