1

I can't figure it out. If I have something like this:

html,body,div {margin:0;padding:0;}
.cont {
  display: flex;
  justify-content: space-between;
  height: 100px;
  background: #eee;
}
.one, .two, .three {width: 150px;}
.one {
  background: #009;
}
.two {
  background: #090;
}
.three {

  background: #900;
}
<div class="cont">

  <div class="one"></div>
  <div class="two"></div>
  <div class="three"></div>

</div>

Then, how would I change the .two, so it would be exactly after the .one without spacing? The self-align didn't work for me, for some reason.

  • It's about flex, of course. Not aligning it at all cost.

  • I want to be able to change only the .two, without touching the other elements.

Is this possible using flex?

Nitin Bisht
  • 5,053
  • 4
  • 14
  • 26
moviluxeg
  • 13
  • 2

1 Answers1

1

Simply adjust the margin of the .two:

html,
body,
div {
  margin: 0;
  padding: 0;
}

.cont {
  display: flex;
  height: 100px;
  background: #eee;
  /* removed this
  justify-content: space-between;*/
}

.one,
.two,
.three {
  width: 150px;
}

.one {
  background: #009;
}

.two {
  background: #090;
  margin-right: auto; /*added this*/
}

.three {
  background: #900;
}
<div class="cont">

  <div class="one"></div>
  <div class="two"></div>
  <div class="three"></div>

</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • Daaaaamn, man! wtf... :) Can you explain it, please? Why is the margin doing it? – moviluxeg Apr 28 '18 at 10:31
  • 1
    @moviluxeg this is the magic of flexbox ;) margin:auto is used to align items and to also distribute the free spacing. By adding marign-right:auto to 2 or margin-left:auto to 3 you make the margin take all the free spacing https://www.w3.org/TR/css-flexbox-1/#auto-margins – Temani Afif Apr 28 '18 at 10:34
  • @moviluxeg here is a good article to understand : https://www.sitepoint.com/quick-tip-how-z-index-and-auto-margins-work-in-flexbox/ – Temani Afif Apr 28 '18 at 10:38
  • damn maaaaan, you're awesome! :) – moviluxeg Apr 28 '18 at 10:39