Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

html - Why do overflow clear margin of p-tag

I just learnt a new "css hack" from my teacher. But he don't know why it works.
I'll explain:

I've on my website a gap (the green line) which I don't want to appear:
enter image description here

the grey one is the nav element, the black is a div which contains the p-tag "some content" which make this gap because of his margin. (I'll post the code at the end of the question).

My solution would be just delete the margin. But my teacher telled me another way. He added overflow: hidden; to the div which contains the p, and poff, the gap is gone.

But how is this possible? Why do overflow affect the margin of an element?

Here's a example code plus a codepen demo:
http://codepen.io/anon/pen/JdQaYv

.container,
.header,
.content{
  margin 0;
  padding: 0;
}
.container{
  background; green;
}
.header{
  background: red;
}
.content{
  background: yellow;
}
.overflow{
  overflow: hidden;
}
<div class="container">
  <div class="header">
    Header
  </div>
  <div class="content">
    <p>Contentcontent</p>
  </div>
</div> 
___________________________________________
<br />
<div class="container">
  <div class="header">
    Header
  </div>
  <div class="content overflow">
    <p>Contentcontent</p>
  </div>
</div> 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The browser always collapses the margins with the nearby margins. When you give an overflow: hidden, it calculates all the contents inside it's box model and makes it confine to the content.

Explanation for BoltClock and anyone else. Sorry about my quick dirty handwriting...

This is the same case with floats too. Floated items do not occupy any space. Have a look here:

div {padding: 5px; border: 1px solid #666;}
<div>
  <div style="float: left;"></div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...