- Home
- /
- Tutorials
- /
- CSS Tutorial
- /
- Flex Container
CSS Flexbox
Flex Container
A Flex Container is an HTML element that uses CSS Flexbox Layout to arrange and align its child elements.
To create a flex container, use:
css
display: flex;When an element becomes a flex container:
- Its direct children become flex items
- Items are arranged in a row by default
- Alignment and spacing become easier to control
- Responsive layouts become simpler to create
Flexbox is one of the most widely used CSS layout systems in modern web development. The supporting concepts are explained in Flex Direction and Justify Content.
Syntax
Flex Container Syntax
css
.container {
display: flex;
}Flex Container Example
css
.container {
display: flex;
}This converts the element into a flex container and its direct children into flex items.
Attributes
| Property | Description | Example |
|---|---|---|
| display: flex | Creates a flex container | display: flex; |
| flex-direction | Defines item direction | flex-direction: row; |
| justify-content | Aligns items horizontally | justify-content: center; |
| align-items | Aligns items vertically | align-items: center; |
| flex-wrap | Controls item wrapping | flex-wrap: wrap; |
Example
Flex Container Complete Example
html
<!DOCTYPE html>
<html>
<head>
<title>Flex Container Example</title>
<style>
.container {
display: flex;
border: 2px solid black;
padding: 10px;
gap: 10px;
}
.item {
background-color: lightblue;
padding: 20px;
border: 1px solid #333;
}
</style>
</head>
<body>
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
</div>
</body>
</html>Browser Support
Feature | Chrome | Edge | Firefox | Safari |
|---|---|---|---|---|
| display: flex | 29 | 12 | 20 | 9 |
Versions show the first stable desktop release with unprefixed support. Data source: MDN Browser Compatibility Data 8.0.8.
Notes
- Flexbox works on direct child elements only.
- The default direction is
row. - Flexbox is ideal for navigation menus, card layouts, toolbars, and responsive sections.
- Modern websites prefer Flexbox over older layout methods like
float.
Before and After Flexbox
Normal Layout
html
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>Output:
text
Item 1
Item 2
Item 3With Flexbox
css
.container {
display: flex;
}Output:
text
Item 1 Item 2 Item 3Conclusion
A Flex Container is the foundation of the Flexbox layout system. By applying display: flex, you gain powerful control over the alignment, spacing, and arrangement of child elements, making it much easier to create modern and responsive web layouts.
