Matt Bindoff
Matt Bindoff

Reputation: 55

CSS negative margin incorrect when using box-sizing: border-box

When setting a negative margin to pull a child element to the boundary of the parent element which has padding, the distance moved isn't correct.

Here's a test case:

<div class='full'>
  full
  <div class='child'>
    child
  </div>
</div>

* {
  box-sizing: border-box;
}

.full {
  width:80%;
  padding-left: 3%;
  background: #000;
  color: #fff;
}
.child {
  margin-left: -3.75%;  /* 3 / 80 * 100 */
  padding-left: 3.75%;
  background: #ddd;
  color: #000;
}

http://codepen.io/anon/pen/fuaxE

If I remove the box-sizing the margin is correct, but with border-box set the negative margin is correct - see the line down the left side of the child element.

Am I missing something obvious?

Upvotes: 0

Views: 910

Answers (1)

DaniP
DaniP

Reputation: 38252

The problem here is you have a miss calculation:

margin-left: -3.75%;  /* 3 / 80 * 100 */

It must be:

margin-left: -3.8961%;  /* 3 / 77 * 100 */

Because the real Width of his parent is 80% - 3% of padding:left. Check this Demo

Upvotes: 1

Related Questions