Why does adding overflow: hidden make the child el

2019-07-11 03:41发布

问题:

When I add an element like h1 with margin: 30px 0;, the margin goes outside the container!

I faced this problem many times before, and I solved it by using overflow: hidden

I want to figure out what's the problem and why this solution works?

Find a JSFiddle here https://jsfiddle.net/LeoAref/zv6c2c2d/

.container {
  background: #ccc;
}
.container.overflow {
  overflow: hidden;
}
.secTitle {
  margin: 30px 0;
}
code {
  color: blue;
}
<!-- secTitle margin goes outside the container -->
<div class="container">
  <h1 class="secTitle">Container without <code>overflow: hidden</code></h1>
</div>

<!-- works fine here -->
<div class="container overflow">
  <h1 class="secTitle">Container with <code>overflow: hidden</code></h1>
</div>

回答1:

Why is this occurring?

In the second example, the margin(s) are collapse when you add overflow: hidden.

Here is the relevant documentation:

Box Model 8.3.1 Collapsing margins

In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.

When two or more margins collapse, the resulting margin width is the maximum of the collapsing margins' widths. In the case of negative margins, the maximum of the absolute values of the negative adjoining margins is deducted from the maximum of the positive adjoining margins. If there are no positive margins, the maximum of the absolute values of the adjoining margins is deducted from zero.

There are specific rules that will prevent the margins from collapsing. One of the rules specified is:

Margins of elements that establish new block formatting contexts (such as floats and elements with 'overflow' other than 'visible') do not collapse with their in-flow children. [link]

In your case, the element has an overflow value other than the default, visible, since it is set to hidden. Thus, the margins don't collapse, and they are contained within the element.

For more workarounds, check out the documentation.



回答2:

.container.overflow

It should be

.container .overflow

.container {
    background: #ccc;
}

.container .overflow {
    overflow: hidden;
}

.secTitle {
    margin: 30px 0;
}

code {
    color: blue;
}
<!-- secTitle margin goes outside the container -->
<div class="container">
    <h1 class="secTitle">
        Container without 
        <code>overflow: hidden</code>
    </h1>
</div>

<!-- works fine here -->
<div class="container overflow">
    <h1 class="secTitle">
        Container with 
        <code>overflow: hidden</code>
    </h1>
</div>



回答3:

Why ? Because margins are meant to be outside the element and here doesn't consider the h1 margins. By default, overflow is at visible and renders outside the h1 container. It's quite hard to explain but I tried ! Hope I helped.