CSS: Make Flexbox's justify content only overflow to the right [duplicate]

南楼画角 提交于 2020-04-13 03:24:53

问题


I have a dynamic number of divs in a single container div with display: flex.

Now, I want my child divs to be centered, so I use justify-content: center. This works perfectly for a small number of children (the blue rectangles)

But for a larger amount of children, setting justify-content: center means that child divs are pushed farther and farther off-screen (the red rectangles).

Children pushed off-screen to the right are still visible because I can just scroll to the right to see the rightmost children.

But children pushed off-screen to the left are not visible because I cannot scroll to the left. This is a problem.

So essentially I want to use flexbox to center its children but prevent the children from being pushed off-screen to the left. Instead, content should overflow to the right, the way that justify-content: flux-start works, but still be centered.


回答1:


Just use nested flex-containers and set margin-left: auto and margin-right: auto for inner flex-container. This will work because auto margins work only when we have free space to distribute. Demo:

.flex {
  display: flex;
}

.inner-flex {
  display: flex;
  margin-left: auto;
  margin-right: auto;
}

/* just styles for demo */
.flex__item {
  background-color: tomato;
  color: white;
  margin: 10px;
  padding: 10px;
}
<div class="flex">
  <div class="inner-flex">
    <div class="flex__item">One</div>
    <div class="flex__item">Two</div>
    <div class="flex__item">Three</div>
    <div class="flex__item">Four</div>
    <div class="flex__item">Five</div>
    <div class="flex__item">Six</div>
    <div class="flex__item">Seven</div>
  </div>
</div>

Here is jsFiddle to test resizing.



来源:https://stackoverflow.com/questions/45420123/css-make-flexboxs-justify-content-only-overflow-to-the-right

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!