Sub topic 3
The flex shorthand and its common values
Assume you know basic HTML, CSS selectors and the cascade, the box model, and units such as px, rem, and percentages.
Sizing and aligning individual items
The flex shorthand sets three properties:
.item {
flex: 1 1 200px; /* grow shrink basis */
}flex-growcontrols how an item shares extra space.flex-shrinkcontrols how it gives up space when the line is too narrow.flex-basissets its starting size.
Common values include:
flex: 1lets items share available space. It commonly behaves like1 1 0%.flex: 0 1 autois the default. Items use their content size and may shrink.flex: 0 0 200pxkeeps an item at 200 pixels. It neither grows nor shrinks.
align-self overrides the container’s align-items value for one item:
.container {
display: flex;
align-items: center;
}
.container .special {
align-self: flex-start;
}When wrapping creates multiple flex lines, align-content distributes those lines across the cross axis. It has no visible effect when there is only one line.
.cards {
display: flex;
flex-wrap: wrap;
align-content: space-between;
gap: 1rem;
}An auto margin consumes available space on its axis. This pushes later items away:
.toolbar {
display: flex;
align-items: center;
}
.toolbar .push-right {
margin-left: auto;
}The order property changes visual order. It does not change the HTML or keyboard reading order. Prefer changing the source order when possible, because visual reordering can confuse keyboard and screen-reader users.
A flex item’s automatic minimum width can prevent shrinking. Long words or URLs may overflow. Set min-width: 0 on a flexible item when it must shrink:
.row {
display: flex;
gap: 0.5rem;
}
.title {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}Patterns and choosing a layout method
Flexbox handles one-dimensional layouts well:
- Navigation:
justify-content: space-between. - Cards:
flex-wrap: wrapwithflex: 1 1 200px. - Centering:
justify-content: centerandalign-items: center. - Sticky footer: a column container with
main { flex: 1; }.
Choose Flexbox when items flow mainly in one row or column. Choose CSS Grid when you need coordinated rows and columns in two dimensions.
Exercise
Why might a flexible title need min-width: 0?
Show answer
Its automatic minimum size can prevent shrinking, so the title overflows instead of allowing ellipsis truncation.