简体   繁体   中英

Customising space between flex items

I am almost fine with the result given by justify-content: space-between , I just would like to have less space between the last two flex items.

I tried to calc() a negative left margin for the last item, but it doesn't fully work: on my browser in full screen, the last two items are separated by more than the supposed 1em calculated, then while shrinking the window, they get closer till they touch. And with further shrinking the last items bounces away.

 .belt { display: flex; justify-content: space-between; padding: 1em; }.belt > * { min-width: 10em; border: solid orange; }.belt > button { margin-left: calc((42em - 100%) / 3 + 1em); }
 <div class='belt'> <a href='/'>LOGO</a> <div>[_______________|Q]</div> <a href='/signin'>Sign in</a> <button>Cart</button> </div>

The calculation I made:

  • To make the calculation possible in first place I had to define a width for the items and I used min-width: 10em; which also works as a width because the content of the items is less than 10em
  • 100% minus the 40em of the four items, minus the two 1em paddings of the container, divided by 3 (the spaces between four items) ---> should be more or less the space between the items when using justify-content: space-between
  • setting the left margin of the last item to a negative value being the result of the expression above should result on having no space between the last two items
  • final step: adding 1em

What's wrong with this approach and what would be a good way to achieve a 1em space between the last two items?

PS: I came to know about this gap property, which unfortunately wouldn't reach 99% of Safari users, so for now is not an option.

I think you can simply use margin:auto on the second item and your 1em margin on the last item:

 .belt { display: flex; justify-content: space-between; padding: 1em; }.belt > * { min-width: 10em; border: solid orange; }.belt > button { margin-left: 1em; }.belt > div { margin:0 auto; }
 <div class='belt'> <a href='/'>LOGO</a> <div>[_______________|Q]</div> <a href='/signin'>Sign in</a> <button>Cart</button> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM