3

Let's consider two items A and B within their container C. When width(C) > width(A)+width(B), I want the items to stay on the same line: A aligned left and B right. But when width(C) < width(A)+width(B), I want them to use their own line, and be centered within C horizontally.

I have achieved all the above except for the latter requirement — centering them when they are on their own line each. How do I do that? Keen to use flexbox but any working solution would be good, even with floats.

.container {
 display: flex;
 flex-wrap: wrap;
  justify-content: space-between;
}
.container div:nth-child(1) {
 background-color: orange;
}
.container div:nth-child(2) {
 background-color: green;
}
<div class="container">
  <div>Item1 Item1 Item1 Item1 Item1</div>
  <div>Item2 Item2 Item2 Item2 Item2</div>
</div>
Lovepreet Singh
  • 128
  • 2
  • 13
Greendrake
  • 3,657
  • 2
  • 18
  • 24
  • May be i don't understand your question but it seems like it's already working to me – Oke Tega Feb 27 '17 at 13:05
  • you will need to use media queries, so have a breakpoint at the point that the divs would go onto their own line and set their margin: auto; – Andrew brough Feb 27 '17 at 13:16
  • Instead of `justify-content: space-between`, consider `justify-content: space-around`: http://stackoverflow.com/q/38290861/3597276 – Michael Benjamin Feb 27 '17 at 13:25
  • @Andrewbrough Using media queries with a breakpoint has a couple of cons, see my comment to *maxshuty's* answer. @Michael_B the items need to be aligned left and right respectively *when they're on the same line*. `space-around` will make them not stick to the edges. – Greendrake Feb 27 '17 at 23:37
  • @Greendrake. yes it the content is not going to be a known width then this makes this not always work. the only alternative that I could see is using js to calculate when to add/remove the css properties based on the sizes of your containers then. – Andrew brough Feb 28 '17 at 15:07

1 Answers1

1

You need to use media queries.

In this jsFiddle I made you can see that with the media query it now is centered, and I used Michael_B's suggestion of justify-content: space-around; and ended up with this:

@media(max-width: 768px) {
  .container {
    justify-content: space-around;
  }
}

You can play with the pixels for your specific usage.

If they must be on a new line when centered then you'll want to play around with something like this fiddle solution I made, basically just adding <br class="hidden"/> and only showing it when the screen is anything <= 768 pixels. Or you can play around with your own solution if you hold grudges against <br/>

Community
  • 1
  • 1
maxshuty
  • 9,708
  • 13
  • 64
  • 77
  • Thanks for that. Your solution is viable but 1) requires to adjust `max-width` whenever the content of *A* or *B* changes; 2) Only works where the container's width is stretched to the browser window; this isn't necessarily the case. – Greendrake Feb 27 '17 at 23:27