Sub topic 1
CSS Flexbox: One-Dimensional Layout in CSS
Prerequisites
This chapter assumes basic HTML, CSS selectors, the cascade, the box model, and units such as px, rem, and percentages.
Creating a Flex Container
Flexbox arranges elements along one main line. An element becomes a flex container when its display property is flex. Its direct children then become flex items. Flexbox does not automatically affect deeper descendants.
<nav class="nav">
<a href="/">Home</a>
<a href="/docs">Docs</a>
<a href="/contact">Contact</a>
</nav>
<style>
.nav {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem;
}
</style>Main Axis and Cross Axis
A flex container has two axes:
- The main axis is the direction in which flex items are laid out.
- The cross axis is perpendicular to the main axis.
By default, the main axis is horizontal. Therefore, justify-content distributes space horizontally, while align-items aligns items vertically.
Choosing a Direction
The flex-direction property chooses the main axis:
rowlays items out from left to right. This is the default.row-reversereverses that horizontal direction.columnlays items out from top to bottom.column-reversereverses that vertical direction.
Changing the direction also changes what the axes mean. With flex-direction: column, justify-content works vertically and align-items works horizontally.
.panel {
display: flex;
flex-direction: column;
justify-content: center;
align-items: stretch;
}Distributing Items Along the Main Axis
justify-content controls free space on the main axis. Common values include:
flex-start: place items at the beginning.center: group items in the middle.space-between: place the first and last items at the edges.space-aroundorspace-evenly: distribute space around items.
Aligning Items on the Cross Axis
align-items controls the cross-axis position of every flex item. Common values include stretch, flex-start, center, and flex-end. An individual item can override the container with align-self.
Exercise
With flex-direction: column, which axis does justify-content control?
Show answer
It controls the vertical main axis.