我会喜欢这个问题的一些眼睛和意见,我正面对着flexbox和一个网格。我将在列表中有可变数量的项目(如在图库中),但每个项目的大小将是固定的。现在,我需要对列表项进行水平居中,并使它们始终对齐。
html {
box-sizing: border-box;
}
p {
padding: 1em;
}
.wrapper {
max-width: 100%;
min-height: 500px;
padding: 2em 0;
background: papayawhip;
border: 1px solid orange;
overflow: hidden;
display: flex;
justify-content: center;
}
ul {
display: flex;
background: mistyrose;
width: 100%;
justify-content: flex-start;
flex-wrap: wrap;
margin: 1em;
border: 1px solid blue;
padding: 0;
}
li {
display: block;
background: indianred;
width: 200px;
height: 200px;
margin: .1em;
/* padding: 1em; */
color: white;
font-size: 2rem;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
align-self: stretch;
border: 1px solid azure;
}
li div {
display: inline-block;
}
<div class="wrapper">
<ul>
<li>
<div>
First
</div>
</li>
<li>
<div>
Second
</div>
</li>
<li>
<div>
Third
</div>
</li>
<li>
<div>
Fourth
</div>
</li>
<li>
<div>
Fifth
</div>
</li>
</ul>
</div>
我一直在努力让它与Flexbox一样工作,并且想知道这是否是我需要使用CSS Grid的情况。
可以在下图中看到所需的行为。考虑期望行为的另一种方式是justify-content: flex-start
,但整个事物(从最左侧列表项的左边缘到最右侧列表项的右边缘)居中。
如果用Flexbox无法实现这一点,那么CSS网格是否可以走?或者可以以不同的方式实现相同的效果?
答案 0 :(得分:-1)
除了justify-content: center
元素之外,您还希望将align-items: center
和ul
添加到li
。这可以在下面看到,this updated fiddle。
html {
box-sizing: border-box;
}
p {
padding: 1em;
}
.wrapper {
width: 100%;
min-height: 500px;
padding: 2em 0;
background: papayawhip;
border: 1px solid orange;
overflow: hidden;
display: flex;
justify-content: center;
}
ul {
display: flex;
background: mistyrose;
width: 100%;
justify-content: center;
align-items: center;
flex-wrap: wrap;
margin: 1em;
border: 1px solid blue;
padding: 0;
}
li {
display: block;
background: indianred;
width: 200px;
height: 200px;
margin: .1em;
/* padding: 1em; */
color: white;
font-size: 2rem;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
align-self: stretch;
border: 1px solid azure;
}
li div {
display: inline-block;
}
/* li:first-child {
padding:
} */
&#13;
<div class="intro">
<p>
My aim is to horizontally center the variable number of red boxes in the display within the following constraints:
<br/> 1. RedBox width stays the same.
<br /> 2. All boxes should be aligned, like a grid.
<br /> 3. Each row of the boxes should have same starting point (as a result of 2)
<br/>
<em>Like shown here: <a href="">Desired Behavior</a> :: So can this be solved via Flexbox or do I need CSS Grid?</em>
</p>
</div>
<div class="wrapper">
<ul>
<li>
<div>
First
</div>
</li>
<li>
<div>
Second
</div>
</li>
<li>
<div>
Third
</div>
</li>
<li>
<div>
Fourth
</div>
</li>
<li>
<div>
Fifth
</div>
</li>
</ul>
</div>
&#13;
希望这有帮助! :)