How to work with Flexbox elements in CSS?

CSS Flexbox is a layout method that allows you to arrange elements in a flexible container. To work with Flexbox, you need to define a flex container (parent element) using display: flex and place flex items (child elements) inside it.

Syntax

.container {
    display: flex;
}

Basic Flexbox Setup

The following example creates a flex container with multiple flex items arranged horizontally −

<!DOCTYPE html>
<html>
<head>
<style>
    .mycontainer {
        display: flex;
        background-color: orange;
        padding: 10px;
    }
    .mycontainer > div {
        background-color: white;
        text-align: center;
        line-height: 40px;
        font-size: 25px;
        width: 100px;
        margin: 5px;
        border-radius: 5px;
    }
</style>
</head>
<body>
    <h1>Quiz</h1>
    <div class="mycontainer">
        <div>Q1</div>
        <div>Q2</div>
        <div>Q3</div>
        <div>Q4</div>
        <div>Q5</div>
        <div>Q6</div>
    </div>
</body>
</html>
A heading "Quiz" appears followed by an orange container with six white rounded boxes labeled Q1 through Q6 arranged horizontally in a row.

Common Flex Properties

You can control flex item behavior using these properties −

<!DOCTYPE html>
<html>
<head>
<style>
    .flex-container {
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: lightblue;
        height: 100px;
        padding: 10px;
    }
    .flex-item {
        background-color: coral;
        padding: 20px;
        text-align: center;
        color: white;
        font-weight: bold;
    }
</style>
</head>
<body>
    <div class="flex-container">
        <div class="flex-item">Item 1</div>
        <div class="flex-item">Item 2</div>
        <div class="flex-item">Item 3</div>
    </div>
</body>
</html>
A light blue container with three coral-colored items evenly distributed across the width, with equal spacing between them and vertically centered.

Conclusion

Flexbox simplifies layout creation by automatically arranging flex items within a flex container. Use display: flex on the parent element to enable flexible layouts with easy alignment and spacing control.

Updated on: 2026-03-15T13:12:00+05:30

240 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements