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.

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

PropertyDescriptionExample
display: flexCreates a flex containerdisplay: flex;
flex-directionDefines item directionflex-direction: row;
justify-contentAligns items horizontallyjustify-content: center;
align-itemsAligns items verticallyalign-items: center;
flex-wrapControls item wrappingflex-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>

Output

Browser Output

css

Three boxes will appear in a horizontal row
Each box will have a light blue background
A gap will appear between the boxes
The parent container will act as a flex container

Browser Support

Chrome
Edge
Firefox
Safari
Opera
IE
YesYesYesYesYesPartial

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 3

With Flexbox

css

.container {
    display: flex;
}

Output:

text

Item 1   Item 2   Item 3

Conclusion

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.