Auto margins and visual order
Definition and purpose
Auto margins in flex layout absorb positive free space before alignment. They can separate groups in a toolbar without changing the logical order of controls. The order property instead changes visual layout order.
Separate actions
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; } #p { width: 300px; } #p > div { background: lightblue; outline: 1px solid navy; } #p { display: flex; } #p > div { width: 50px; } #c { margin-inline-start: auto; } </style> </head> <body> <div id="p"> <div id="a">A</div> <div id="b">B</div> <div id="c">C</div> </div> </body></html>The last item absorbs 150px of free space at its start.
Syntax and mental model
In a row, margin-inline-start: auto on the last item can push it toward the inline end. order accepts integers; lower values are placed first, ties follow source order. For keyboard and reading order, keep the source meaningful rather than relying on visual rearrangement.
Visual order with decorative boxes
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; } #p { width: 300px; } #p > div { background: lightblue; outline: 1px solid navy; } #p { display: flex; } #p > div { width: 50px; } #c { order: -1; } </style> </head> <body> <div id="p"> <div id="a">A</div> <div id="b">B</div> <div id="c">C</div> </div> </body></html>C paints first in the flex layout; the markup is still A, B, C.
Common mistakes
Do not use order as a substitute for logical DOM order. Auto margins cannot absorb negative free space; they do not guarantee that overflowing items fit.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Automatic minimum sizes. Next lesson: Nested flex and baseline alignment.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Auto margins and visual order — knowledge check
Five questions on auto margins and visual order.
When are auto margins resolved relative to justify-content?
Which margin pushes the final item to inline end in a normal row?
Which order value appears first among -1, 0 and 2?
What should determine keyboard navigation order?
Can auto margins distribute negative free space?