我希望 flex 元素居中,但是当我们有第二行时,有 5 个(来自下图)在 1 之下并且不在父项中居中。
这是我所拥有的示例:
ul {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
margin: 0;
padding: 0;
}
li {
list-style-type: none;
border: 1px solid gray;
margin: 15px;
padding: 5px;
width: 200px;
}
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
最佳答案
Flexbox 挑战与局限
挑战是将一组 flex 元素居中并将它们左对齐。但是除非每行有固定数量的框,并且每个框都是固定宽度的,否则目前使用 flexbox 是不可能的。
使用问题中发布的代码,我们可以创建一个新的 flex 容器来包装当前的 flex 容器 (ul
),这样我们就可以将 ul
居中使用 justify-content: center
。
然后 ul
的 flex 元素可以与 justify-content: flex-start
左对齐。
#container {
display: flex;
justify-content: center;
}
ul {
display: flex;
justify-content: flex-start;
}
这将创建一组居中的左对齐 flex 元素。
此方法的问题在于,在某些屏幕尺寸下,ul
右侧会出现间隙,使其不再居中显示。
发生这种情况是因为在 flex 布局(实际上,通常是 CSS)中,容器:
- 不知道元素何时换行;
- 不知道以前占用的空间现在是空的,并且
- 不会重新计算其宽度以收缩包裹较窄的布局。
右边空白的最大长度是容器期望在那里的 flex 元素的长度。
在下面的演示中,通过水平调整窗口大小,您可以看到空格来来去去。
更实用的方法
使用 inline-block
和 media queries 可以在没有 flexbox 的情况下实现所需的布局。
HTML
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
CSS
ul {
margin: 0 auto; /* center container */
width: 1200px;
padding-left: 0; /* remove list padding */
font-size: 0; /* remove inline-block white space;
see https://stackoverflow.com/a/32801275/3597276 */
}
li {
display: inline-block;
font-size: 18px; /* restore font size removed in container */
list-style-type: none;
width: 150px;
height: 50px;
line-height: 50px;
margin: 15px 25px;
box-sizing: border-box;
text-align: center;
}
@media screen and (max-width: 430px) { ul { width: 200px; } }
@media screen and (min-width: 431px) and (max-width: 630px) { ul { width: 400px; } }
@media screen and (min-width: 631px) and (max-width: 830px) { ul { width:600px; } }
@media screen and (min-width: 831px) and (max-width: 1030px) { ul { width: 800px; } }
@media screen and (min-width: 1031px) and (max-width: 1230px) { ul { width: 1000px; } }
上面的代码呈现了一个水平居中的容器,其中的子元素像这样左对齐:
其他选项
Properly sizing and aligning the flex item(s) on the last row
-
Masonry is a JavaScript grid layout library. It works by placing elements in optimal position based on available vertical space, sort of like a mason fitting stones in a wall. You’ve probably seen it in use all over the Internet.
source: http://masonry.desandro.com/
CSS Grid Layout Module Level 1
This CSS module defines a two-dimensional grid-based layout system, optimized for user interface design. In the grid layout model, the children of a grid container can be positioned into arbitrary slots in a predefined flexible or fixed-size layout grid.
关于html - 如何将 flex 容器居中但左对齐 flex 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49845268/