Center wrapped items in a space-between flexbox

后端 未结 2 2249
忘了有多久
忘了有多久 2021-02-14 10:46

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

2条回答
  •  别那么骄傲
    2021-02-14 11:04

    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

提交回复
热议问题