互动挑战
首先,我们为您提供一个由我们的 学习伙伴 Scrimba 创建的有趣、交互式的 flexbox 挑战。
观看嵌入的 scrim,并按照说明编辑代码,完成时间线上的所有任务(小幽灵图标)。完成后,您可以继续观看 scrim,以检查老师的解决方案与您的解决方案有何不同。
任务 1
在此任务中,列表项是网站的导航。要完成此任务,请使用 flexbox 将列表项布局为一行,并在每个项目之间留出相等的空间。
您的最终结果应如下面的图片所示

html
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About Us</a></li>
<li><a href="/products">Our Products</a></li>
<li><a href="/contact">Contact Us</a></li>
</ul>
</nav>
css
body {
font: 1.2em / 1.5 sans-serif;
}
nav ul {
max-width: 700px;
list-style: none;
padding: 0;
margin: 0;
}
nav a:link,
nav a:visited {
background-color: #4d7298;
border: 2px solid #77a6b6;
border-radius: 0.5em;
color: white;
padding: 0.5em;
display: inline-block;
text-decoration: none;
}
nav ul {
/* Add styles here */
}
点击此处显示解决方案
您可以应用 display: flex 并使用 justify-content 属性控制间距。
css
nav ul {
display: flex;
justify-content: space-between;
}
任务 2
在此任务中,列表项的大小各不相同,但我们希望它们显示为三等宽的列,无论每个项目包含什么内容。
您的最终结果应如下面的图片所示

奖励题:您现在能让第一个项目的大小是其他项目的两倍吗?
html
<ul>
<li>I am small</li>
<li>I have more content than the very small item.</li>
<li>
I have lots of content. So much content that I don't know where it is all
going to go. I'm glad that CSS is pretty good at dealing with situations
where we end up with more words than expected!
</li>
</ul>
css
body {
font: 1.2em / 1.5 sans-serif;
}
ul {
max-width: 700px;
list-style: none;
padding: 0;
margin: 0;
}
li {
background-color: #4d7298;
border: 2px solid #77a6b6;
border-radius: 0.5em;
color: white;
padding: 0.5em;
}
ul {
/* Add styles here */
}
li {
/* Add styles here */
}
点击此处显示解决方案
最好使用简写属性,因此在这种情况下,flex: 1 可能是最佳答案,因此最理想的结果是
css
ul {
display: flex;
}
li {
flex: 1;
}
对于奖励题,添加一个定位器来选择第一个元素,并将其设置为 flex: 2;(或 flex: 2 0 0; 或 flex-grow: 2)。
css
li:first-child {
flex: 2;
}
任务 3
在此任务中,我们希望您将列表项排列成如下面的图像所示的行。

html
<ul>
<li>Turnip</li>
<li>greens</li>
<li>yarrow</li>
<li>ricebean</li>
<li>rutabaga</li>
<li>endive</li>
<li>cauliflower</li>
<li>sea lettuce</li>
<li>kohlrabi</li>
<li>amaranth</li>
</ul>
css
body {
font: 1.2em / 1.5 sans-serif;
}
ul {
width: 450px;
list-style: none;
padding: 0;
margin: 0;
}
li {
background-color: #4d7298;
border: 2px solid #77a6b6;
border-radius: 0.5em;
color: white;
padding: 0.5em;
margin: 0.5em;
}
ul {
/* Add styles here */
}
li {
/* Add styles here */
}
点击此处显示解决方案
此任务需要理解 flex-wrap 属性来换行 flex 行。此外,为了确保最终效果与示例相似,您需要为子元素设置 flex: auto(或 flex: 1 1 auto;)。
css
ul {
display: flex;
flex-wrap: wrap;
}
li {
flex: auto;
}