PhD PhD - 2 months ago 27
CSS Question

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

A common trick for vertical positioning elements is to use the following CSS:

.item {
position:absolute;
top:50%;
margin-top:-8px; /* half of height */
height: 16px;
}


When seen in the metric view as in Chrome this is what you see:

enter image description here

However, there is no visual margin depicted when you hover over the element i.e. the margin is 'outside' the border and can be visualized. But negative margins don't show up. How do they look and what is it that makes it different?

Why is
margin-top:-8px
not the same as
margin-bottom:8px
?

So just how do negative margins work and what's the intuition behind them. How do they 'bump up' (in case of
margin-top < 0
) an item?

Answer Source

Negative margins are valid in css and understanding their (compliant) behaviour is mainly based on the box model and margin collapsing. While certain scenarios are more complex, a lot of common mistakes can be avoided after studying the spec.

For instance, rendering of your sample code is guided by the css spec as described in calculating heights and margins for absolutely positioned non-replaced elements.

If I were to make a graphical representation, I'd probably go with something like this (not to scale):

negative top margin

The margin box lost 8px on the top, however this does not affect the content & padding boxes. Because your element is absolutely positioned, moving the element 8px up does not cause any further disturbance to the layout; with static in-flow content that's not always the case.

Bonus:

Still need convincing that reading specs is the way to go (as opposed to articles like this)? I see you're trying to vertically center the element, so why do you have to set margin-top:-8px; and not margin-top:-50%;?

Well, vertical centering in CSS is harder than it should be. When setting even top or bottom margins in %, the value is calculated as a percentage always relative to the width of the containing block. This is rather a common pitfall and the quirk is rarely described outside of w3 docos