Flexbox: Negative margin, why does this work?

Viewed 1779

So I was playing around with a layout and I kind of stumbled across a cool trick, but I don't know why it works? Link to example.

http://codepen.io/TaylorHuston/pen/NNjZqZ

<div id="container">
  <div id="left">
  </div>
  <div id="right">
    <button id="expand">Expand</button>
  </div>
</div>

.....

body {
  background-color: green;
}
#container {
  display: flex;
  background-color: white;
  width: 1300px;
  height: 500px;
  margin: 0px auto; 
}

#left {
  background-color: grey;
  width: 0;
  transition: all .2s ease;
}

#left.expanded {
  width: 300px;
}

#right {
  flex: 0 0 100%;
  margin-right: -400px;
}

....

$('#expand').click(function() {
  $('#left').toggleClass('expanded');
});

With that code, when you click on the 'expand' button, the left column expands out to 300px wide, and the right column is pushed over 300px. And it is actually pushed over, it doesn't just shrink to accordingly. If no negative margin is set though, nothing happens, since #right is 100% width. Why does a negative margin allow the #right to be pushed when there is something to the left of it, but doesn't actually move or affect it when there isn't?

0 Answers
Related