Home > Web Front-end > CSS Tutorial > How to Prevent Margin-Top from Affecting a Borderless Parent Element?

How to Prevent Margin-Top from Affecting a Borderless Parent Element?

Linda Hamilton
Release: 2024-11-25 15:28:11
Original
720 people have browsed it

How to Prevent Margin-Top from Affecting a Borderless Parent Element?

Solve the problem of CSS Margin-top in borderless parent elements

When the parent element has no top border, the margin- of the child element top may cause the parent element to move downwards. This problem can be solved by adding a top border to the parent element, but this goes against the original requirement.

However, there is an alternative solution that prevents this from happening:

Apply overflow:auto to the parent element

by adding overflow: With auto applied to a parent element, you can force its container to contain its content, thus preventing margin-collapsing. Margin-collapsing is a behavior in CSS that merges adjacent margins into a single margin.

In the example given, you can add the following CSS to the .body class:

.body {
  overflow: auto;
}
Copy after login

This will stop the margin-top from causing the .body to move down while keeping its top clear frame.

Reference

  • [W3C CSS2 Specification: Margin Collapse](http://www.w3.org/TR/CSS2/box.html# collapsing-margins)

The above is the detailed content of How to Prevent Margin-Top from Affecting a Borderless Parent Element?. 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