1

I built a simple page using FlexBox CSS, and I don't understand why when I use a percent margin on one of the items, the width of the container is not expanding.

Note: Problems exists in Chrome / FireFox.

Code Pen: https://codepen.io/dsomekh/pen/QvGvrq

Example:

<html>
<style>
.page{
    display:flex;
    /*border: 5px solid orange;*/
}

.container{

display:flex;
border: 5px solid orange;
}
.item_left{
display:flex;
margin-right:25%;
}

.item_right{
display:flex;

}
</style>
<div class="page">
    <div class="container">
        <div class="item_left">Left</div>
        <div class="item_right">Right</div>
    </div>
</div>
</html>
David Somekh
  • 795
  • 3
  • 12
  • 33

2 Answers2

1

You're using flexbox wrong.

try

.container{
  display:flex;
}

.item_left {
  flex: 1;
  border: 5px solid orange;
  margin-right:25%;
}

.item_right {
  flex: 1;
  border: 5px solid orange;
}
<div class="page">
 <div class="container">
  <div class="item_left">Left</div>
  <div class="item_right">Right</div>
 </div>
</div>
Jean Mayer
  • 11
  • 1
  • 7
  • Your code causes the two items in the container expand through the entire page. Is there some way to avoid it? – David Somekh Apr 25 '17 at 19:39
  • May I ask what is wrong with OP's code? – Asons Apr 25 '17 at 20:07
  • @DavidSomekh It is the lack of using `display: flex` for the `.page`, together with using `flex: 1` on the items, that cause it to use full page width. Remove the `flex: 1` and you'll see yet another layout. – Asons Apr 25 '17 at 20:10
0

As Michael Coker commented, Authors should avoid using percentages in paddings or margins on flex items entirely, as they will get different behavior in different browsers. (CSS Flexbox margins)

When using percent we often relate that to the viewport width, so with that in mind, viewport units vw/vh can be a good option, since it works similar (responsive).

Stack snippet made of your Codepen sample

.page {
  display: flex;
  /*border: 5px solid orange;*/
}

.container {
  display: flex;
  border: 5px solid orange;
}

.item_left {
  flex: 1;
  margin-right: 25vw;
}

.item_right {
  display: flex;
  flex: 1;
}
<div class="page">
  <div class="container">
    <div class="item_left">Left</div>
    <div class="item_right">Right</div>
  </div>
</div>

Stack snippet made of your questions code

.page {
  display: flex;
  /*border: 5px solid orange;*/
}

.container {
  display: flex;
  border: 5px solid orange;
}

.item_left {
  display: flex;
  margin-right: 25vw;
}

.item_right {
  display: flex;
}
<div class="page">
  <div class="container">
    <div class="item_left">Left</div>
    <div class="item_right">Right</div>
  </div>
</div>
Community
  • 1
  • 1
Asons
  • 84,923
  • 12
  • 110
  • 165