Saturday, 18 January 2025

Flex Your Layout Skills: Understanding CSS Flexbox

Flexbox, or the Flexible Box Layout, is a layout model in CSS that allows you to design complex layouts more easily and efficiently. It provides a way to align and distribute space among items within a container, even when their size is unknown or dynamic.

 

The display: flex property is used to create a flex container. Once a container is defined as a flex container, its children become flex items, which can be arranged in flexible ways.

 

Basic Terminology

1.   Flex Container: The element with display: flex.

2.   Flex Items: The direct children of the flex container.

 

Flex layout has two invisible axes,

1.   Main Axis

2.   Cross Axis

 

Flex always positions the items on Main axis. By default, main axis is horizontal.

 


We can change the default axis to vertical by setting the flex-direction to column.

flex-direction: column

 

When flex-direction is set to column, items are aligned vertically.

 


 

‘justify-content’ property is used to align the flex items along the main axis.

‘align-content’ property is used to align the flex items along the cross axis.

 

Hello World Application

To start using Flexbox, you need to define a container element as a flex container using the display: flex property.

.container {
    display: flex;
    border: 2px solid black;
    padding: 10px;
}

hello-world.html

<!DOCTYPE html>
<html>
<head>
    <style>
        .container {
            display: flex;
            border: 2px solid black;
            padding: 10px;
        }

        .item {
            background-color: green;
            padding: 20px;
            margin: 10px;
            color: white;
        }
    </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>



 

In this example, the .container div is set as a flex container, and its direct children, the .item divs, become flex items. By default, flex items are laid out in a row.

Previous                                                    Next                                                    Home

No comments:

Post a Comment