1

I am trying out flex for the first time. I thought this would align perfectly, with even spaces in between, but for some reason the margin-right acts on the last box.

How can I get them to space evenly with the correct margin-right: 3% on box one and two, but not three, without overriding margin using: margin-right: 0% !important;.

I get this:

flex issue where boxes do not allign

What am I doing wrong?

/* boxes sit in a page area div */
#pageArea {
  width: 96%;
  margin: 0px auto;
  padding: 0% 0 0% 0;
}


/* flex */
.evenly {
  display: flex;
  justify-content: space-between;
  border: solid;
}

.item {
  white-space: nowrap;
  background: gray;
  width: 33%;
  border: 1px solid #DBDBDB;
  margin: 0 3% 5% 0;
}
<div class="evenly">
  <div class="item" id="item1">Item One</div>
  <div class="item" id="item2">Item # Two</div>
  <div class="item" id="item3">Item Three</div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
davvv
  • 772
  • 1
  • 6
  • 24

3 Answers3

1

instead of using margin set the width of your items only. this will cause the space-between property to work correctly

.item {
  white-space:nowrap;
  background:gray;
  width: 30%;   /* reduced to 30% */
  border: 1px solid #DBDBDB;
  /*margin: 0 3% 5% 0;*/
}
kev670
  • 810
  • 2
  • 18
  • 37
1

Instead of:

.item { margin-right: 3% }

use

.item + .item { margin-left: 3% }

The original selector is saying: all items get a right margin

The revised selector is saying: only items that immediately follow an item get a left margin. This excludes a left margin on the first item.

#pageArea {
  width: 96%;
  margin: 0px auto;
  padding: 0% 0 0% 0;
}
.evenly {
  display: flex;
  justify-content: space-between;
  border: solid;
}

.item {
  white-space: nowrap;
  background: gray;
  width: 33%;
  border: 1px solid #DBDBDB;
  margin: 0 0 5% 0;
}

.item+.item {
  margin-left: 3%;
}
<div class="evenly">
  <div class="item" id="item1">Item One</div>
  <div class="item" id="item2">Item # Two</div>
  <div class="item" id="item3">Item Three</div>
</div>

And keep in mind that percentage margins and padding in flexbox behave differently across browsers. Why doesn't percentage padding work on flex items in Firefox?

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
0

/* boxes sit in a page area div */
#pageArea {
    width: 96%;
    margin: 0px auto;
    padding: 0% 0 0% 0;
}  

/* flex */
.evenly {
      display:flex;
      justify-content:space-between;
      border:solid;
}

.item {
      white-space:nowrap;
      background:gray;
      width: 32%; /* (100 - 3*2)/3 */
      border: 1px solid #DBDBDB;
      margin: 0 0 5% 0;
}
<div class="evenly">
  <div class="item" id="item1">Item One</div>
  <div class="item" id="item2">Item # Two</div>
  <div class="item" id="item3">Item Three</div>
</div>

The justify-content:space-between; can calculate the space automatically, no need to use the margin.

shuizhongyuemin
  • 559
  • 5
  • 11