Home > Web Front-end > CSS Tutorial > Negative Margins in CSS: Why Is margin-top:-5 Not the Same as margin-bottom:5?

Negative Margins in CSS: Why Is margin-top:-5 Not the Same as margin-bottom:5?

Mary-Kate Olsen
Release: 2024-11-11 03:07:02
Original
245 people have browsed it

Negative Margins in CSS: Why Is margin-top:-5 Not the Same as margin-bottom:5?

Delving into Negative Margins: Behavior, Intuition, and Differences

CSS allows for negative margins, but their effects can be confusing. To demystify this topic, let's explore their behavior and understand why margin-top:-5 is not equivalent to margin-bottom:5.

Understanding Negative Margins

Negative margins are applied outside the border and are invisible in the visual margin. This is because they affect the margin box while leaving the content and padding boxes untouched. For absolutely positioned elements, negative margins move the element by the specified amount without affecting the layout.

Graphical Representation

Imagine an element with a negative top margin:

[Image of a rectangle with a negative top margin]

The margin box shrinks by the negative amount, but the content and padding boxes remain unaffected.

Intuition Behind Negative Margins

Negative margins "bump up" an element because they decrease the size of the margin box. For margin-top < 0, this causes the element to move upwards.

Difference Between Top and Bottom Margins

margin-top:-8px is not the same as margin-bottom:8px because of margin collapsing. When an element has both negative and positive margins on opposite sides, the margins collapse, eliminating the negative margin. As a result, no net movement occurs.

Bonus Tip for Vertical Centering

When using % for lateral margins (i.e., top or bottom), the value is computed as a percentage of the width of the containing block. This can lead to issues with vertical centering. It's better to use margin-top:-50vh for vertical centering, where vh denotes the unit for the viewport height.

The above is the detailed content of Negative Margins in CSS: Why Is margin-top:-5 Not the Same as margin-bottom:5?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template