CSS Flex Container
A Flex Container is a parent element that uses display: flex; to create a Flexbox layout.
Once an element becomes a flex container, its direct child elements automatically become flex items.
What is a Flex Container?
A Flex Container is the parent element that controls the layout of its direct children.
We create a Flex Container by applying display: flex; to an element.
The elements directly inside that container become Flex Items.
Basic Syntax
.container {
display: flex;
}
The display: flex; declaration changes the parent element into a Flex Container.
Flex Container Structure
Blue outer area = Flex Container
Inner elements = Flex Items
Parent and Child Relationship
Flexbox works through a parent-child relationship. Only the direct children of a Flex Container become Flex Items.
<div class="container">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
</div>
Here, the outer div.container is the Flex Container.
The three inner div elements are Flex Items.
Example: Creating a Flex Container
Consider a course website containing three technology cards. We can use Flexbox to place the cards in a row.
.course-container {
display: flex;
gap: 15px;
padding: 20px;
border: 3px solid #2563eb;
background-color: #dbeafe;
}
.course {
flex: 1;
background-color: lightblue;
border: 2px solid blue;
padding: 20px;
text-align: center;
}
Output
Important Flex Container Properties
| Property | Purpose |
|---|---|
| display | Defines an element as a Flex Container. |
| flex-direction | Defines the direction of Flex Items. |
| flex-wrap | Controls whether items move to another line. |
| justify-content | Controls alignment along the main axis. |
| align-items | Controls alignment along the cross axis. |
| align-content | Controls spacing between multiple flex lines. |
| gap | Creates space between Flex Items. |
display: flex
The most important declaration for Flexbox is display: flex;.
.container {
display: flex;
}
Without display: flex;, the element behaves according to the normal CSS layout rules.
After applying display: flex;, the direct children become Flex Items and Flexbox properties can be used to control their layout.
Real-World Example
Suppose CIIT Training Institute has three course cards: C#, Java, and Python.
Instead of manually positioning every card, Flexbox can place them inside one container and control their spacing and alignment.
.courses {
display: flex;
gap: 15px;
}
.course {
flex: 1;
}
This approach makes the layout easier to maintain and adapt for different screen sizes.
Summary
A Flex Container is a parent element created by applying display: flex;. Its direct children automatically become Flex Items. The Flex Container controls the layout using properties such as flex-direction, flex-wrap, justify-content, align-items, align-content, and gap.