Why does a border border a border?

In this JSFiddle , the text sits poorly at the top and bottom of the pink parent div. However, when you remove the pink border from the pink parent div, a space exists between the text and the parent div.

Why is this happening?

Here is my CSS:

.bodyCopy {
  background: pink;
  border: 1px solid pink;
}

p {
  line-height: 28px;
  margin-bottom: 20px;
}

.bodyCopy > p:first-child {
  margin-top: -9px;
}

.bodyCopy > p:last-child {
  margin-bottom: -9px;
}
+4
source share
4 answers

I think this is due to the collapse of the margin. Without a border, a border can collapse with spaces around it. It seems that the margin has no effect, since you want it to refer to .bodyCopy. Adding border: 1px solid pinkmakes field collapse impossible. For positive fields, this is more clear; collapsing for negative fields seems a little strange, in my opinion.

, , https://developer.mozilla.org/en-US/docs/Web/CSS/margin_collapsing .

.

.container {
  padding: 10px;
}

.box {
  background-color: #f99;
}

.border {
  border: 1px solid #c66;
}

.positive-margin {
  margin: 10px 0;
}

.negative-margin {
  margin: -10px 0;
}

p {
  margin: 0;
}
<div class="container">
  <div class="box">
    <p>box</p>
  </div>
</div>

<div class="container">
  <div class="box">
    <p class="positive-margin">box positive-margin</p>
  </div>
</div>

<div class="container">
  <div class="box">
    <p class="negative-margin">box positive-margin</p>
  </div>
</div>

<div class="container">
  <div class="box border">
    <p class="positive-margin">box positive-margin border</p>
  </div>
</div>

<div class="container">
  <div class="box border">
    <p class="negative-margin">box negative-margin border</p>
  </div>
</div>
Hide result
+2

, div, .

, , , , : http://jsfiddle.net/es91825w/ p >

.bodyCopy {
    background: pink;
    border: 1px solid pink;
    padding: 3px;
}
0

-9px <p> div bocyCopy, p, .

, <p> div bocyCopy, <p> 0px.

0
source

The border prevents the collapse of the vertical margins of your paragraphs, and as you roll around negative margins, they will expand. Coagulation in this sense means simply getting rid. This explains the collapse of the fields.

http://www.sitepoint.com/web-foundations/collapsing-margins/

In a nutshell, you can give your .bodyCopy div a 1px padding (and adjust the paragraph margins to 1px to compensate) to prevent this from happening.

0
source

All Articles