Andrew's Digital Garden

Negative margin

Negative margin can be a good way to cancel out padding, or make elements overlap. It allows an element to reserve space outside of where it would usually sit in the document flow.

As a simple example, think about a card component with padding, but you want to abut something to the left edge. You can cancel out the padding with an equivalent negative margin to achieve this, without touching the padding at all.

Using a positive and matching negative margin, you can allow elements to use more space than they visually appear to. e.g. generating a 4px buffer for a focus state to render in. Focus states can be especially annoying as using overflow: hidden or similar can cut off a conditional focus state.

Negative margins can also be good dealing with flex containers + gap. Depending on your setup, the gap of a flex container can affect the available space of your flex items [[20250623124005-flex-items-per-row]]. To help with this, you can apply padding on flex items in one direction, and a negative margin in that same direction on the flex container. I've used this in the past for 'Inline' components, or even Columns, Grid, or Matrix components. Anything that has an unknown amount of items that need a consistent space between them. This lets the outer bounds of the component be 'full width', and the gap is applied only between items.

When using negative margin, the direction can be important. I recommend using a negative left margin, as a negative right margin can often introduce a scrollbar to a page, or a full width element. Using a negative left margin won't draw scrollbars (assuming the default writing mode).

Ensure the negative margin doesn't exceed the padding of the parent it's contained within. If it does, then you've made an element that's too big and this can also introduce a scrollbar.

Note that this technique can often be a bit misleading. Often people think there's 'extra' padding, or the alignment is incorrect, even if it produces the correct result. For [[designsystem]]s it can also be confusing, as you want to keep the padding and negative margin values in sync, which can be a tricky API to make.

https://css-tricks.com/negative-margins/

[[20200402104023-components-margin]]

[[css]] [[layout]] [[web]]

Negative margin