gpt4 book ai didi

html - 如何将 flex 容器居中但左对齐 flex 元素

转载 作者:技术小花猫 更新时间:2023-10-29 11:32:10 24 4
gpt4 key购买 nike

我希望 flex 元素居中,但是当我们有第二行时,有 5 个(来自下图)在 1 之下并且不在父项中居中。

enter image description here

这是我所拥有的示例:

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>

http://jsfiddle.net/8jqbjese/2/

最佳答案

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 右侧会出现间隙,使其不再居中显示。

enter image description here enter image description here

发生这种情况是因为在 flex 布局(实际上,通常是 CSS)中,容器:

  1. 不知道元素何时换行;
  2. 不知道以前占用的空间现在是空的,并且
  3. 不会重新计算其宽度以收缩包裹较窄的布局。

右边空白的最大长度是容器期望在那里的 flex 元素的长度。

在下面的演示中,通过水平调整窗口大小,您可以看到空格来来去去。

DEMO


更实用的方法

使用 inline-blockmedia 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; } }

上面的代码呈现了一个水平居中的容器,其中的子元素像这样左对齐:

enter image description here

DEMO


其他选项

关于html - 如何将 flex 容器居中但左对齐 flex 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32802202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com