Jakob
Jakob

Reputation: 529

Center wrapped items in a space-between flexbox

For a navigation section, I want it to use space-between justification. For smaller displays where the navigation might have to wrap, I'd like the items to center themselves, as opposed to sticking to the left when alone on a row.

nav {
  display: flex;
  width: 100%;
  flex-flow: row wrap;
  justify-content: space-between;
}
<nav>
  <div class='item'>
    Item 1 is alone on its row if the window is small, but is not centered.
  </div>
  <div class='item'>
    Item 2 is very much like item 1.
  </div>
</nav>

Codepen demo: https://codepen.io/anon/pen/MmdOMP?editors=1100#0

Upvotes: 13

Views: 3289

Answers (2)

Ursu Alexandr
Ursu Alexandr

Reputation: 308

There can be 2 solutions from my point of view:

  1. Use CSS media queries or;
  2. JS solution, explained below:

When item is wrapped it takes 100% width, what you need to do is to check on window resize event the width of the item, and if it is 100% relative to the parent element that means it was wrapped, you can add a class at this point and remove it when the statement is false:

function justifyCenter() {
    var navWidth = $("nav").width();
    var itemWidth = $(".item:first-child").width();

    if (navWidth === itemWidth ) {
        $("nav").addClass('justify-center');
    } else {
        $("nav").removeClass('justify-center');
    }
}

Codepen demo: https://codepen.io/anon/pen/WzgpLw

Upvotes: 3

Kalnode
Kalnode

Reputation: 11366

LGSon's comment makes sense to me, but presumably OP wants the ability to modify dynamic text that may or may not fit in a container, regardless of flexbox config or media query.

Look into JS that detects line wraps, then triggers an action (e.g. centering the text).

For example: https://github.com/xdamman/js-line-wrap-detector

Or, JS that automatically resizes text to fit within a container. Useless for all kinds of situations.

For example: http://www.fittextjs.com

Upvotes: 0

Related Questions