HTML & CSSMedium
Main axis vs cross axis?
In Flexbox, the main axis is the direction items are laid out in, set by flex-direction, and the cross axis runs perpendicular to it. justify-content aligns items along the main axis and align-items aligns them along the cross axis, so when you switch from row to column, those two properties swap their visual effect.
How the axes follow flex-direction
flex-direction | Main axis | Cross axis |
|---|---|---|
row (default) | Horizontal (inline direction) | Vertical |
column | Vertical | Horizontal |
row-reverse / column-reverse | Same axis, reversed start and end | Unchanged |
Which property works on which axis
- Main axis:
justify-content,flex-grow,flex-shrink,flex-basis,gapbetween items,order. - Cross axis:
align-items,align-self,align-content(for wrapped lines).
Practical consequences
- In a
columncontainer,justify-content: centercenters vertically, andalign-items: centercenters horizontally. flex-basissets width in a row and height in a column.- The axes are logical: in a right-to-left document,
rowruns right to left; in vertical writing modes the main axis ofrowis vertical.
Grid comparison
Grid uses two fixed axes instead: inline (columns, justify-*) and block (rows, align-*), regardless of any direction setting.
Interview tip
A quick way to remember: justify follows the flow (main axis), align goes across it.
Code example
html
1<style>2 body { font-family: system-ui; display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }3 .box { display: flex; height: 160px; border: 2px solid #0b1020; gap: 6px; padding: 6px;4 justify-content: center; /* main axis */5 align-items: flex-end; } /* cross axis */6 .row { flex-direction: row; background: #dbeafe; }7 .column { flex-direction: column; background: #fef9c3; }8 .box span { background: #2b4bff; color: white; padding: 4px 8px; border-radius: 4px; }9 h4 { margin: 0 0 4px; }10</style>11<div>12 <h4>row: main = horizontal</h4>13 <div class="box row"><span>1</span><span>2</span><span>3</span></div>14</div>15<div>16 <h4>column: main = vertical</h4>17 <div class="box column"><span>1</span><span>2</span><span>3</span></div>18</div>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.