Home  >  Article  >  Web Front-end  >  Why Does Margin-Top Push Down Parent Divs, and How Can I Fix It Without Using Borders?

Why Does Margin-Top Push Down Parent Divs, and How Can I Fix It Without Using Borders?

Barbara Streisand
Barbara StreisandOriginal
2024-11-26 22:47:14823browse

Why Does Margin-Top Push Down Parent Divs, and How Can I Fix It Without Using Borders?

How to Fix Margin-top Pushing Down Parent Div Without Border

When a child element with a margin-top sits inside a parent element with no top border, the margin can push down the parent element. This behavior is often undesirable. One solution is to add a top border to the parent element, but this is not always possible or desirable.

An alternative solution is to use the overflow: auto property on the parent element. This will prevent the margin from collapsing and pushing down the parent element. Here is an example:

.body {
    border: 1px solid black;
    border-top: none;
    border-bottom: none;
    width: 150px;
    height: 112px;
    background-color: lightgreen;
    overflow: auto;
}

.body .container {
    background-color: blue;
    height: 50px;
    width: 50%;
    margin-top: 30px;
}

With this change, the orange div will no longer push down the green div.

The above is the detailed content of Why Does Margin-Top Push Down Parent Divs, and How Can I Fix It Without Using Borders?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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