CSS Flexbox is a layout model that allows you to create flexible and efficient layouts. It provides a way to arrange items within a container, helping you control alignment, spacing, and the overall design. Flexbox is especially useful for creating responsive, one-dimensional layouts (either row or column based).
To use Flexbox, you simply set the display property of the parent container to flex:
.container {
display: flex;
}
The flex-direction property defines how the flex items are laid out inside the flex container.
Example:
.container {
flex-direction: row;
}
The justify-content property aligns the flex items along the main axis (the primary axis set by flex-direction).
Options:
Example:
.container {
justify-content: space-between;
}
The align-items property controls how flex items are aligned along the cross axis (the opposite axis of the main axis).
Options:
Example:
.container {
align-items: center;
}
The flex-wrap property specifies whether flex items should wrap onto multiple lines if they don’t fit in a single row or column.
Options:
Example:
.container {
flex-wrap: wrap;
}
The align-content property aligns the flex lines when there’s extra space along the cross axis (only applies when flex-wrap is used).
Options:
Example:
.container {
align-content: space-between;
}
These properties allow you to control how flex items grow and shrink relative to each other and define their initial size.
flex-grow: Determines how much a flex item will grow relative to others.
Example:
.item {
flex-grow: 2;
}
flex-shrink: Specifies how much a flex item will shrink if there’s not enough space.
Example:
.item {
flex-shrink: 1;
}
flex-basis: Sets the initial size of the flex item before the remaining space is distributed.
Example:
.item {
flex-basis: 200px;
}
Flexbox is great for building responsive, one-dimensional layouts where elements need to align and space themselves properly. It’s particularly useful when creating flexible components such as navigation bars, card layouts, or grid-based systems where items need to adjust their size based on available space.
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
</div>
.container {
display: flex;
justify-content: space-around;
align-items: center;
height: 200px;
}
.item {
flex-grow: 1;
padding: 10px;
}
absolute position property.This exercise will reinforce the concepts of Flexbox and when to apply the position property effectively.