CSS Flexbox
CSS Flexbox (Flexible Box Layout) is a layout model that allows you to design complex layouts in a more efficient and predictable way than traditional CSS. It enables responsive design by aligning items within a container, even when their size is unknown or dynamic.
Key Concepts of Flexbox
- Flex Container: The parent element that holds the flex items. You need to set the display property to
flex
orinline-flex
. - Flex Items: The child elements of a flex container that are laid out according to the flexbox model.
Setting Up a Flex Container
To create a flex container, use the display
property with the value flex
or inline-flex
.
.flex-container {
display: flex;
}
Flex Container Properties
- flex-direction: Defines the direction flex items are placed in the flex container. Values:
row
,row-reverse
,column
,column-reverse
. - flex-wrap: Controls whether flex items should wrap onto multiple lines. Values:
nowrap
,wrap
,wrap-reverse
. - justify-content: Aligns flex items along the main axis. Common values include
flex-start
,flex-end
,center
,space-between
,space-around
. - align-items: Aligns flex items along the cross axis. Values include
flex-start
,flex-end
,center
,baseline
,stretch
. - align-content: Aligns flex lines within the flex container when there is extra space. It works only if there are multiple lines of flex items.
Example: Basic Flexbox Layout
.flex-container {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
}
.flex-item {
flex: 1; /* Each item takes up equal space */
padding: 10px;
background-color: #ccc;
}
Item 1
Item 2
Item 3
Flex Item Properties
- flex-grow: Defines the ability of a flex item to grow relative to the rest of the flex items in the container. Default is 0.
- flex-shrink: Defines the ability of a flex item to shrink if necessary. Default is 1.
- flex-basis: Defines the default size of an element before the remaining space is distributed. It can be a fixed value or a percentage.
- align-self: Allows the default alignment (or the one specified by
align-items
) to be overridden for individual flex items.
Example: Flex Item Properties
.flex-item {
flex: 2; /* Item will grow twice as much as others */
}
.flex-item-2 {
flex: 1; /* Item will grow normally */
}
Item 1
Item 2
Item 3
Description
- Use Flexbox for One-Dimensional Layouts: Flexbox is ideal for laying out items in a single dimension (row or column).
- Combine with Other Layouts: Flexbox can be used alongside CSS Grid for more complex layouts.
- Test Across Devices: Always test your layouts on various screen sizes to ensure proper alignment and spacing.