Neat trick with flex box and margin block auto

Margin-block-auto can be a smart way to work faster and smarter with flex box elements. It allows you to automatically adjust the vertical margin of an element based on the available space within its container.

Here’s how it works

When applied to an element, margin-block-auto dynamically calculates and distributes the available space within its container equally, pushing the element away from its adjacent elements.

.container {
display: flex;
}

.container div:nth-child(2) {
margin-block-start: auto;
}

Tip: one of the most common use cases of margin-block-auto is vertical centering of elements within their containers. By setting margin-block-auto to both top and bottom margins of an element, it can be vertically centered within its parent container irrespective of its height.

Margin-block-auto dynamically calculates and distributes the available space within its container equally, pushing the element away from its adjacent elements

Dmitry Mayorov talks about margin block auto in more depths here

Scroll to Top