Once an element has display: flex, its direct children automatically become flex items, arranged by default in a single horizontal row, each sized based on its content unless told otherwise, with the parent's other flex properties, like flex-direction, justify-content, and align-items, controlling their exact direction, alignment, and spacing. This is fundamentally different from float-based layouts, since flex items participate in a purpose-built one-dimensional layout algorithm designed specifically for distributing space and aligning items along a single axis, rather than relying on the side effects of floating and clearing elements out of normal flow.
1Understanding Display: flex
Once an element has display: flex, its direct children automatically become flex items, arranged by default in a single horizontal row, each sized based on its content unless told otherwise, with the parent's other flex properties, like flex-direction, justify-content, and align-items, controlling their exact direction, alignment, and spacing. This is fundamentally different from float-based layouts, since flex items participate in a purpose-built one-dimensional layout algorithm designed specifically for distributing space and aligning items along a single axis, rather than relying on the side effects of floating and clearing elements out of normal flow.
Setting display: flex only affects the flex container's direct children — grandchildren and deeper descendants are unaffected as flex items unless they themselves are also inside their own separate flex container.
.navbar {
display: flex;
justify-content: space-between;
}2Practical Example
Here is a real-world application of Display: flex showing how it is used in production CSS code.
.card {
display: flex;
align-items: center;
gap: 12px;
}3Best Practices
Follow these guidelines when working with Display: flex:
1. Reach for display: flex as the default modern approach for one-dimensional layouts, rows or columns of items needing alignment or space distribution, rather than float-based techniques
2. Remember flex properties on a container only affect its direct children, not deeper-nested descendants, unless those descendants are themselves flex containers too
3. Combine display: flex with justify-content and align-items as the standard trio for controlling both horizontal and vertical alignment of items within the container
Tip: Setting display: flex only affects the flex container's direct children — grandchildren and deeper descendants are unaffected as flex items unless they themselves are also inside their own separate flex container.
.navbar {
display: flex;
justify-content: space-between;
}