将包装好的物品放在Flexbox之间的空间中 [英] Center wrapped items in a space-between flexbox

查看:80
本文介绍了将包装好的物品放在Flexbox之间的空间中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于导航部分,我希望它使用space-between对齐方式.对于可能需要包装导航的较小的显示器,我希望这些物品居中放置,而不是独自一人排在左边.

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演示: https://codepen. io/anon/pen/MmdOMP?editors = 1100#0

推荐答案

从我的角度来看,可以有两种解决方案:

There can be 2 solutions from my point of view:

  1. 使用CSS媒体查询或
  2. JS解决方案,如下所述:

包裹物品时,它的宽度为100%,您需要做的是检查窗口调整大小事件的宽度,如果物品相对于父元素而言是100%,则意味着包裹它的宽度此时添加一个类,并在语句为false时将其删除:

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演示: https://codepen.io/anon/pen /WzgpLw

这篇关于将包装好的物品放在Flexbox之间的空间中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆