Codectionary / Developer documentation / CSS

Alignment with Flex Auto Margins

An auto margin on a flex item absorbs available space on its axis before ordinary alignment is applied.

What it is and why to use it

An auto margin on a flex item absorbs available space on its axis before ordinary alignment is applied. It is useful for placing one action at the far end of a toolbar without introducing empty spacer elements. Logical margins also adapt more naturally to document direction.

Common mistakes and limitations

Auto margins can leave no free space for justify-content to distribute, so combining both may not behave as expected. Multiple auto margins share available space. Allow wrapping or another narrow-screen arrangement when items no longer fit.

Try the example

The example pairs editable CSS with its own HTML preview. Run it, then change one declaration at a time and compare the result. Locally, put the CSS in a style element in the document head or in an external stylesheet linked from the HTML. Feature support varies by browser and version; use the linked reference and a useful fallback where needed.

HTML used by this example

<div class="toolbar"><strong>Study notes</strong><button class="action">Save</button></div>

Syntax

margin-inline-start: auto;

Examples

Alignment with Flex Auto Margins

Run the CSS against the supplied HTML, then experiment with the values.

.toolbar { display: flex; align-items: center; gap: .75rem; border: 1px solid #94a3b8; padding: 1rem; }
.action { margin-inline-start: auto; }
  1. The toolbar establishes a flex formatting context.
  2. The action’s start-side auto margin consumes remaining inline space, separating it from the title.
  3. The button remains at the end while the gap still supplies spacing when free space becomes small. This is useful for header actions.
HTML used by this example
<div class="demo"><div class="toolbar"><strong>Study notes</strong><button class="action">Save</button></div></div>

Best practices

  • Auto margins can leave no free space for justify-content to distribute, so combining both may not behave as expected. Multiple auto margins share available space. Allow wrapping or another narrow-screen arrangement when items no longer fit.
  • Inspect the relevant browser reference and test the browsers used by your audience.

Runtime & versions

Web browsers. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

CSS specifications (modules)

Specifications & further reading