CSS Flexbox
CSS Flexbox is a one-dimensional layout model that provides a method to offer space distribution and powerful alignment capabilities.
Key Concepts
- Flex Container: The parent element that has display: flex applied to it.
- Flex Items: The direct children of the flex container.
- Main Axis: The primary axis along which flex items are laid out.
- Cross Axis: The axis perpendicular to the main axis.
Creating a Flex Container
To create a flex container, use:
.container {
ㅤdisplay: flex;
}
Flex Container Properties
- flex-direction: Defines the direction of the main axis (row, column, row-reverse, column-reverse).
- justify-content: Aligns flex items along the main axis.
- align-items: Aligns flex items along the cross axis.
- flex-wrap: Controls whether flex items are forced into a single line or can be wrapped onto multiple lines.
- align-content: Aligns a flex container's lines within the flex container when there is extra space on the cross-axis.
Flex Item Properties
- flex-grow: Defines the ability for a flex item to grow if necessary.
- flex-shrink: Defines the ability for a flex item to shrink if necessary.
- flex-basis: Defines the default size of an element before the remaining space is distributed.
- align-self: Allows the default alignment to be overridden for individual flex items.
- order: Controls the order in which flex items appear in the flex container.
Example
.container {
ㅤdisplay: flex;
ㅤjustify-content: space-between;
ㅤalign-items: center;
}
.item {
ㅤflex: 1 1 200px;
}
Best Practices
- Use Flexbox for one-dimensional layouts (either rows or columns).
- Combine Flexbox with media queries for responsive designs.
- Consider using Flexbox for navigation menus and equally spaced items.
- Use flex-grow, flex-shrink, and flex-basis together with the flex shorthand for more control.
- Remember that Flexbox is not supported in very old browsers, so always provide fallbacks.
CSS Flexbox provides a powerful and flexible way to create responsive layouts. It's particularly useful for distributing space and aligning content in complex ways, making it an essential tool for modern web design.