CSS:使Flexbox的合理内容仅向右溢出 [英] CSS: Make Flexbox's justify content only overflow to the right
问题描述
在具有display: flex
的单个容器div中,我有一个动态的div.
I have a dynamic number of divs in a single container div with display: flex
.
现在,我希望我的孩子div居中,因此我使用justify-content: center
.
这非常适合少数儿童(蓝色矩形)
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)
但是对于较大数量的孩子,设置justify-content: center
意味着将孩子div推离屏幕越来越远(红色矩形).
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.
所以从本质上讲,我想使用flexbox
将其子级居中,但要防止将子级从屏幕外向左推.相反,内容应该向右溢出,即justify-content: flux-start
的工作方式,但仍应居中.
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.
推荐答案
只需使用嵌套的flex-container,并为内部flex-container设置margin-left: auto
和margin-right: auto
.这将起作用,因为仅当我们有可用空间可分配时,自动边距才起作用.演示:
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>
这里是 jsFiddle 以测试调整大小.
Here is jsFiddle to test resizing.
这篇关于CSS:使Flexbox的合理内容仅向右溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!